TypeScript1-TypeScript 简介及环境搭建

一、JavaScript 自有类型系统的问题

1. 强类型语言和弱类型语言

强类型语言和弱类型语言是编程语言的两种不同类型,它们之间的主要区别在于变量的数据类型和转换规则。

强类型语言

强类型语言是指在编写代码时需要明确指定变量的数据类型,并且编译器或解释器会在编译或运行时对变量进行类型检查,以确保程序的正确性和安全性。

在强类型语言中,当一个对象从调用函数传递到被调用函数时,其类型必须与被调用函数中声明的类型一致。不允许改变变量的数据类型,除非强制进行转换。如果程序中出现了类型不匹配的错误,编译器或解释器会直接报错。

一些常见的强类型语言包括 Java、C++ 和 Python(Python 3 以上版本)。

弱类型语言

弱类型语言则不需要明确指定变量的数据类型,而是允许在运行时根据需要随时转换变量的类型。这种灵活性给编程带来了很大的方便,但也可能导致一些潜在的问题,比如类型错误、安全漏洞等。

一些常见的弱类型语言包括 JavaScript、PHP 和 Python(Python 2.x版本)。

2. 静态类型语言和动态类型语言

静态类型语言和动态类型语言是编程语言的两种不同类型,它们之间的主要区别在于变量的数据类型的确定方式和类型检查的时机。

静态类型语言

静态类型语言是指在编写代码时需要明确指定变量的数据类型,并且编译器会在编译时对变量进行类型检查,以确保程序的正确性和安全性。如果程序中出现了类型不匹配的错误,编译器会直接报错。

静态类型语言对类型极度严格,能立即发现错误,运行时良好。静态类型语言在编译时能够发现许多潜在的问题,从而提高代码的可靠性和可维护性。

一些常见的静态类型语言包括 Java、C++、C# 和 Scala 等。

动态类型语言

动态类型语言则不需要明确指定变量的数据类型,而是允许在运行时根据需要随时转换变量的类型。

这种灵活性给编程带来了很大的方便,但也可能导致一些潜在的问题,比如类型错误、安全漏洞等。

动态类型语言对类型非常宽松,bug 隐蔽性高,运行时性能差,可读性较差。但性能是可以改善的,灵活性有些时候更重要。隐蔽性强的bug 可以通过单元测试发现。可读性问题可以通过文档工具进行改善。

一些常见的动态类型语言包括 Python、Ruby、JavaScript、PHP 和 Perl 等。

3. JavaScript 存在的一些问题

JavaScript 是一种弱类型语言,同时也是一种动态类型语言,类型系统相对比较灵活,这也是它被广泛使用的一个原因。但它的灵活性也导致了一些问题,包括以下几点:

(1) 隐式类型转换问题:JavaScript 允许在运行时进行隐式类型转换,这可能导致程序出现难以预料的行为。比如,数字类型和字符串类型的加法操作会自动将数字类型转换为字符串类型。

(2) 动态类型问题:JavaScript 的类型是在运行时动态确定的,而不是在编译时确定的。这意味着开发人员需要非常小心地管理变量的类型,以确保程序的正确性。

(3) 弱类型问题:虽然 JavaScript 提供了一些类型检查的机制,但是它仍然是一种弱类型语言。这意味着开发人员需要更多地关注类型问题,以避免出现类型错误和安全漏洞。

(4) 对象类型问题:JavaScript 中的对象是非常灵活的,它们可以动态地添加和删除属性。这可能导致代码中存在未定义的属性和方法,从而导致程序出现错误。

(5) 数组类型问题:JavaScript 中的数组可以存储不同类型的数据,这使得程序很难管理数组中的元素类型。

虽然JavaScript的类型系统存在一些问题,但这并不影响它在 Web 开发中的广泛应用。开发人员可以通过使用一些辅助工具(例如 TypeScript)来提高代码的类型安全性。

二、TypeScript 简介

TypeScript 是一种由微软开发的开源编程语言,它是 JavaScript的 超集,通过添加静态类型和其他一些新特性来增强 JavaScript。TypeScript 最初是由 Anders Hejlsberg 在2012年推出的,目的是使 JavaScript 的开发更加高效和可靠。

TypeScript 支持所有 JavaScript 语法,同时还添加了类、接口、命名空间、泛型等特性,并支持ES6、ES7以及更高级的 ECMAScript 的新特性。与 JavaScript 不同的是,TypeScript 需要在编译时进行类型检查,并在编译时将代码转换为纯 JavaScript 代码,因此可以提高代码的可靠性和可维护性。

TypeScript 可以与现有的 JavaScript 代码无缝集成,并且可以在任何现代浏览器和操作系统上运行。TypeScript 还有丰富的工具支持,包括 Visual Studio Code、WebStorm、Atom 等,同时还有大量的社区支持和开源库可供使用。

TypeScript的主要优势包括:

(1) 增强代码的可读性和可维护性;

(2) 提供类型安全和代码提示;

(3) 增强代码的重构能力;

(4) 提高开发效率。

三、TypeScript 环境搭建及项目初始化

1. 安装 Node.js

Node.js 安装教程网上有很多,这里就不过多赘述,请自行上网查找。建议安装最新的版本,我的 Node.js 版本为 16.18.1.

2. 全局安装 TypeScript

打开控制台,输入命令 npm i typescript -g,全局安装 TypeScript。

3. 初始化项目

创建一个项目文件夹(使用英文命名)。打开控制台,进入已经创建好的项目文件夹,输入命令 npm init -y,初始化一个项目。

会在项目根目录下生成一个 package.json 文件,内容如下:

{
  "name": "ts-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

输入命令 tsc -h 可以查看 TypeScript 的一些命令帮助。

4. 初始化 ts(从现在开始,把 TypeScript 简称为 ts) 配置文件

控制台输入命令 tsc --init,初始化 ts 的配置文件。

会在项目根目录下生成一个 tsconfig.json 文件,其中有 ts 的配置信息。内容如下:

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for legacy experimental decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    // "moduleResolution": "node10",                     /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "allowImportingTsExtensions": true,               /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
    // "resolvePackageJsonExports": true,                /* Use the package.json 'exports' field when resolving package imports. */
    // "resolvePackageJsonImports": true,                /* Use the package.json 'imports' field when resolving imports. */
    // "customConditions": [],                           /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "allowArbitraryExtensions": true,                 /* Enable importing files with any extension, provided a declaration file is present. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "verbatimModuleSyntax": true,                     /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

5. 在项目根目录下新建一个 src 文件夹,就可以开始编写 ts 代码了!

四、第一个 ts 文件

1. 在 src 目录下新建一个 ts 文件,命名为 index.ts,输入如下内容:

let str: string = 'hello ts';

2. 控制台输入命令 tsc ./src/index.ts,编译 index.ts 文件。编译完成后会发现 src 目录下多了一个 index.js 文件,就是 index.ts 文件编译后的结果。

这里介绍一个使用 ts 的过程中非常好用的一个小工具。

(1) 进入 ts 官网的 playground

(2) 在左边的代码编辑器中放入我们编写的 ts 代码,右侧区域就会生成编译后的 js 代码。

(3) 将上述代码的 str 变量改为 20,会发现右侧出现一个报错, number 不能赋值给 string 类型的变量。

五、构建工具 webpack 的配置

1. 安装 webpack

控制台输入命令 npm i webpack webpack-cli webpack-dev-server -D 安装 webpack、webpack 脚手架和 webpack 开发服务器。

2. 配置 webpack

(1) 项目根目录下新建 config 文件夹,用来放 webpack 的配置文件。

(2) config 目录下新建 webpack 配置入口文件 webpack.config.js。

const {merge} = require('webpack-merge')
const baseConfig = require('./webpack.base.config')
const devConfig = require('./webpack.dev.config')
const proConfig = require('./webpack.pro.config')

// 指定开发环境还是生产环境
let config = process.NODE_ENV === 'development' ? devConfig : proConfig;

module.exports = merge(baseConfig, config);

这一步需要控制台输入命令 npm i webpack-merge 安装 merge 包。 

(3) config 目录下新建公共配置文件 webpack.base.config.js。

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  // 指定入口文件
  entry: {
    'app': './src/index.ts'
  },
  // 指定输出文件位置
  output: {
    filename: './bundle.js',
    path: path.resolve('dist')
  },
  resolve: {
    // 指定扩展名
    extensions: ['.js', '.ts', 'tsx']
  },
  module: {
    // ts-loader 配置
    rules: [{
      test: /\.tsx?$/i,
      use: [{
        loader: 'ts-loader'
      }],
      exclude: /node_modules/
    }]
  },
  // 插件
  plugins: [
    new HtmlWebpackPlugin({
      // 生成模板文件路径
      template: './src/tpl/index.html'
    })
  ]
}

需要安装 ts loader,控制台输入命令:npm i ts-loader typescript -D。

还需要安装 HtmlWebpackPlugin 插件,控制台输入 npm i html-webpack-plugin -D 命令。在 src 目录下新建 tpl 文件夹,在 tpl 目录下新建 index.html 文件(就是上面 HtmlWebpackPlugin 插件中配置的路径),输入以下内容:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>TS one</title>
</head>
<body>
 <div class="app"></div>
</body>
</html>

(4) config 目录下新建 webpack 开发环境配置文件 webpack.dev.config.js。

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  devServer: {
    port: 3000
  }
}

(5) config 目录下新建 webpack 生产环境配置文件 webpack.pro.config.js。

const {CleanWebpackPlugin} = require('clean-webpack-plugin')

module.exports = {
  plugins: [
    new CleanWebpackPlugin()
  ]
}

这一步需要控制台输入命令 npm i clean-webpack-plugin -D 安装 CleanWebpackPlugin 插件。

(6) 在 package.json 中的 "scripts" 下加入开发环境和生产环境的脚本 "start" 和 "build"。修改后的 package.json 如下:

{
  "name": "ts-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack serve --mode=development --config ./config/webpack.config.js",
    "build": "webpack --mode=production --config ./config/webpack.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^4.0.0",
    "html-webpack-plugin": "^5.5.1",
    "ts-loader": "^9.4.2",
    "typescript": "^5.0.4",
    "webpack": "^5.81.0",
    "webpack-cli": "^5.0.2",
    "webpack-dev-server": "^4.13.3"
  },
  "dependencies": {
    "webpack-merge": "^5.8.0"
  }
}

六、运行项目

1. 控制台输入 npm run start 启动项目。出现如下信息则为启动成功:

2. 浏览器输入网址 http://localhost:8080/ 即可进入主页面,会发现没有任何内容。

3. 修改 index.ts 内容,保存后会发现页面有了对应变化。

let str: string = 'hello ts';

document.querySelectorAll(".app")[0].innerHTML = str;

4. 控制台输入命令 npm run build,打包构建项目。构建完成后,项目根目录下会多出一个 dist 文件夹,里面就是项目打包之后的内容,之后就可以部署到服务器上了。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晴雪月乔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值