TypeSript
本文档大部分内容来源于 博客 https://ts.xcatliu.com/, 少部分代码重新测试修改整理而成。
TS和JS的区别
JavaScript
JavaScript 是一种轻量级的解释性脚本语言,可嵌入到 HTML 页面中,在浏览器端执行,能够实现浏览器端丰富的交互功能,为用户带来流畅多样的用户体验。
JavaScript 是基于对象和事件驱动的,无需特定的语言环境,只需在支持的浏览器上就能运行。
JavaScript 语言具有以下特点:
- JavaScript 是一种脚本编写语言,无需编译,只要嵌入 HTML 代码中,就能由浏览器逐行加载解释执行。
- JavaScript 是一种基于对象的语言,可以创建对象同时使用现有对象。但是 Javascript 并不支持其它面向对象语言所具有的继承和重载功能。
- JavaScript 的语法简单,使用的变量为弱类型。
- JavaScript 语言较为安全,仅在浏览器端执行,不会访问本地硬盘数据。
- JavaScript 语言具有动态性。JavaScript 是事件驱动的,只根据用户的操作做出相应的反应处理。
- JavaScript 只依赖于浏览器,与操作系统的因素无关。因此 JavaScript 是一种跨平台的语言。
- JavaScript 兼容性较好,能够与其他技术(如 XML,REST API 等)一起使用。
TypeScript
TypeScript 是 Microsoft 开发和维护的一种面向对象的编程语言。它是 JavaScript 的超集,包含了 JavaScript 的所有元素,可以载入 JavaScript 代码运行,并扩展了 JavaScript 的语法。
TypeScript 具有以下特点:
- TypeScript 是 Microsoft 推出的开源语言,使用 Apache 授权协议
- TypeScript 增加了静态类型、类、模块、接口和类型注解
- TypeScript 可用于开发大型的应用
Js 和 Ts的主要差异
TypeScript 可以使用 JavaScript 中的所有代码和编码概念,TypeScript 是为了使 JavaScript 的开发变得更加容易而创建的。例如,TypeScript 使用类型和接口等概念来描述正在使用的数据,这使开发人员能够快速检测错误并调试应用程序
- TypeScript 从核心语言方面和类概念的模塑方面对 JavaScript 对象模型进行扩展。
- JavaScript 代码可以在无需任何修改的情况下与 TypeScript 一同工作,同时可以使用编译器将 TypeScript 代码转换为 JavaScript。
- TypeScript 通过类型注解提供编译时的静态类型检查。
- TypeScript 中的数据要求带有明确的类型,JavaScript不要求。
- TypeScript 为函数提供了缺省参数值。
- TypeScript 引入了 JavaScript 中没有的**“类”的概念**。
- TypeScript 中引入了模块的概念,可以把声明、数据、函数和类封装在模块中。
Hello World
安装TypeScript
- 通过npm(Node.js包管理器)
npm install -g typescript
构建你的第一个TypeScript文件
在编辑器,将下面的代码输入到greeter.ts
文件里:
function greeter(person) {
return "Hello, " + person;
}
let user = "Jane User";
document.body.innerHTML = greeter(user);
编译代码
我们使用了.ts
扩展名,但是这段代码仅仅是JavaScript而已。 你可以直接从现有的JavaScript应用里复制/粘贴这段代码。
在命令行上,运行TypeScript编译器:
tsc greeter.ts
输出结果为一个greeter.js
文件,它包含了和输入文件中相同的JavsScript代码。 一切准备就绪,我们可以运行这个使用TypeScript写的JavaScript应用了!
创建配置文件
往往在书写Typescript项目的时候 都会有一些编译环境等内容的配置,这是时候我们使用 tsc --init
创建一个 tsconfig.json
配置文件
在项目根目录中执行 tsc --init
命令
>tsc --init
Created a new tsconfig.json with:
TS
target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
You can learn more at https://aka.ms/tsconfig
此处观察项目根目录中出现已成功创建了tsconfig.json,大致内容如下,笔者此处生成的目标文件语法为ES2016
,此处手动改成ES2015
{
"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": "ES2015", /* 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": "./js/", /* 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. */
}
}
在html中使用编译后的js
INFO
此时测试编译成js并在html
中使用
- 编写
index.ts
- 使用
tsc index.ts
编译ts文件 - 编写
index.html
使用 编译后的index.js - 在
LiveServer
(此处使用VS Code工具并安装Live Load Server插件能够实时刷新)中打开index.html
- 在浏览器中点击按钮执行js程序
function hello(name: string) {
console.log('hello: ' + name);
}
function invoke() {
let myName: string = '张飞'
hello(myName);
let el = document.createElement('h1');
el.innerHTML = `英雄名称:${myName}`
document.body.appendChild(el)
}
function hello(name) {
console.log('hello: ' + name);
}
function invoke() {
var myName = '张飞';
hello(myName);
var el = document.createElement('h1');
el.innerHTML = "\u82F1\u96C4\u540D\u79F0:".concat(myName);
document.body.appendChild(el);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="index.js"></script>
</head>
<body>
<button type="button" onclick="invoke()">执行编译完的js代码</button>
</body>
</html>
点击html中的按钮后看到如下效果
代码中ts的语法简单说明
在 TypeScript 中,我们使用 :
指定变量的类型,:
的前后有没有空格都可以。
上述例子index.ts中let myName: string = '张飞'
,我们用 :
指定 myName
参数类型为 string
。但是编译为 js 之后,并没有什么检查的代码被插入进来。
这是因为 TypeScript 只会在编译时对类型进行静态检查,如果发现有错误,编译的时候就会报错。而在运行时,与普通的 JavaScript 文件一样,不会对类型进行检查。
下面尝试把这段代码编译一下:
扩展
如何在控制台直接运行ts
为了学习Typescript语法,每次都单独编译后再在html控制台中查看内容比较繁琐,此处暂时不使用工程化的开发方式如webpack、nodejs等工具,本篇博客使用vscode的 Code Runner
插件让Typescript在vscode
控制台中直接运行,具体配置请参考外部超链接,
运行结果如下图所示
function hello(param:string){
console.log('say Hi -->'+param);
}
let myName:string = '张飞'
//运行 hello
hello(myName)
提示:
typescript可以把多个文件编译成一个文件,如编译成一个index.js是可以,仅仅是此处未使用
- 将
tsconfig.json
中编译属性中的module
改为system
- 将outFile属性指定一个具体的目标文件 `"outFile": "./dist/index.js",
- 关闭outDir,即注释该选项
在nodejs中使用TS
主要操作步骤如下
- 初始化nodejs项目
- 开启Typescript依赖
- 安装nodejs类型
- 使用命令创建一个tsconfig.json文件
- 编写ts代码
- 配置热重载功能
- 创建支持清理和编译的生成版本
初始化项目
初始化项目的目的是创建所有node项目的配置文件package.json
npm init -yes
开启Typescript依赖
安装ts编译器,此处采用的是局部安装,也可以采用全局安装即 -g
,详情参考 Hello World 中安装Typescript
npm install typescript --save-dev
安装nodejs类型
npm install @types/node --save-dev
@types/node
就是Node.js的类型提示模块,安装之后TS就可以识别Node.js中的API和数据类型了。然后我们需要创建一个
创建tscofig.json文件
同样在helloworld中已经创建过的可以忽略此步骤
npx tsc --init --rootDir src --outDir dist --esModuleInterop --resolveJsonModule --lib es6,dom --module commonjs --allowJs true --noImplicitAny true --target es2015
编写ts代码
此处可以编写任意的ts代码进行测试
let name:string = 'zhangfei '
console.log(name)
执行编译命令npx tsc
或者tsc
,在项目目录中会自动创建dist/index.js
文件,内容如下
"use strict";
let helloUser = 'zhangfei ';
console.log(helloUser);
配置热重载功能
它将监听你的代码自动进行执行某些命令(此处执行tsc
命令自动编译 ),本功能依赖nodemon模块
安装命令 npm install --save-dev ts-node nodemon
, 命令中添加了一个可选的模块ts-node 它的作用是将ts文件直接编译成js并且执行完成后打印出js的执行结果
项目根目录创建nodemon.json
文件
{
"watch": [
"src"
],
"ext": ".ts,.js",
"ignore": [],
"exec": "npx tsc"
}
上述配置文件观察的是src目录下的ts和js文件的变动,一旦监视到文件发生变动后就执行命令
npx tsc
重新编译
在package,json
新增一个脚本命令"start:dev": "nodemon"
完整的package.json文件如下
{
"name": "ts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start:dev": "nodemon",
},
"keywords": [],
"author": "金山老师",
"license": "ISC",
"dependencies": {
"typescript": "^5.3.3"
},
"devDependencies": {
"@types/node": "^20.11.16",
"nodemon": "^3.0.3",
"ts-node": "^10.9.2"
}
}
在命令行执行npm run start:dev
,就可以自动监听文件更改了
编译前清理
如果需要再编译前清理 dist文件夹可以 通过shell的 rm命令,也可以使用rmiraf
工具,让nodemon模块在监视执行 tsc命令前执行清理的动作
- 安装rmiraf
npm install --save-dev rimraf
- 编辑nodemon.json文件,修改exec 添加
rimraf ./dist
{
"watch": [
"src"
],
"ext": ".ts,.js",
"ignore": [],
"exec": "rimraf ./dist && npx tsc"
}
