1. 高级类型
交叉类型
交叉类型是将多个类型合并为一个类型,例如,Person & Serializable & Loggable
同时是Person
和Serializable
和Loggable
。 就是说这个类型的对象同时拥有了这三种类型的成员。
function extend<T, U>(first: T, second: U): T & U {
const result = {};
for (const id in first) {
(result as any)[id] = (first as any)[id];
}
for (const id in second) {
if (!result.hasOwnProperty(id)) {
(result as any)[id] = (second as any)[id];
}
}
return result as T & U;
}
class Person {
constructor(public name: string) {
this.name = name;
}
}
interface Loggable {
log(): void;
}
class ConsoleLogger implements Loggable {
log() {
// ...
}
}
const jim = extend(new Person('Jim'), new ConsoleLogger());
const n = jim.name;
jim.log();
联合类型
联合类型表示一个值可以是几种类型之一。 我们用竖线(|
)分隔每个类型,所以number | string | boolean
表示一个值可以是number
,string
,或boolean
。
如果一个值是联合类型,我们只能访问此联合类型的所有类型里共有的成员。
interface Bird {
fly();
layEggs();
}
interface Fish {
swim();
layEggs();
}
function getSmallPet(flag): Fish | Bird {
// ...
if (flag === 1) {
return {
fly() {
// todo
},
layEggs() {
// todo
}
};
} else {
return {
swim() {
// todo
},
layEggs() {
// todo
}
};
}
}
const pet = getSmallPet(1);
pet.fly(); // 报错
pet.layEggs(); // ok
类型保护
上例中,我们明确知道pet类型为Bird,但访问fly却报错,此时,需要用类型断言pet类型,才能规避报错
const pet = getSmallPet(1) as Bird;
除此,我们还可以有如下方式:
自定义类型保护
const CheckType = {
// 如果此处不用类型包含,那么myPet.length就会报错
isString(str: any): str is string {
return Object.prototype.toString.call(str).toLocaleLowerCase() === '[object string]';
}
};
function handle(myPet: boolean|string) {
if (CheckType.isString(myPet)) {
console.log(myPet.length);
}
}
typeof
类型保护####
typeof
类型包含会自动被编译器识别,但要注意如下规则:
typeof
类型保护只有两种形式能被识别:typeof v === "typename"
和typeof v !== "typename"
,"typename"
必须是"number"
,"string"
,"boolean"
或"symbol"
。 但是TypeScript并不会阻止你与其它字符串比较,语言不会把那些表达式识别为类型保护。
instanceof
类型保护####
instanceof
的右侧要求是一个构造函数,TypeScript将细化为:
- 此构造函数的
prototype
属性的类型,如果它的类型不为any
的话- 构造签名所返回的类型的联合
断言手动去除null, undefined
语法是添加!
后缀:identifier!
从identifier
的类型里去除了null
和undefined
类型别名
type Name = string;
类型别名会给一个类型起个新名字。 类型别名有时和接口很像,但是可以作用于原始值,联合类型,元组以及其它任何你需要手写的类型。
同接口一样,类型别名也可以是泛型 - 我们可以添加类型参数并且在别名声明的右侧传入:
type Container<T> = { value: T };
interface vs type
- 接口创建了一个新的名字,可以在其它任何地方使用, type并未新建一个类型,而是新名字引用那个类型,当鼠标悬停到某个type类型,显示的是type引用的原始类型
- type不能(或者被)extends, implements
- interface不能描述一个联合类型,元组类型
索引类型
function pluck<T, K extends keyof T>(o: T, names: K[]): T[K][] {
return names.map((key) => o[key]); // o[key] is of type T[K]
}
keyof T
,索引类型查询操作符,对于任何类型T
,keyof T
的结果为T
上已知的公共属性名的联合。
第二个操作符是T[K]
,索引访问操作符
映射类型
经常会需要,将每个属性都变为可选的
interface Person {
name: string;
age: number;
}
type Partial<T> = {
[P in keyof T]?: T[P]
}
type PersionPartial = Partial<Person>;
const zhangsan: PersionPartial = {
name: '123'
}; // ok
下面看看最简单的类型映射:
type Keys = 'option1' | 'option2';
type Flags = { [K in Keys]: boolean };
[P in Keys]: boolean
就是映射类型,具有三部分:
- 类型变量
P
,它会依次绑定到每个属性。 - 字符串字面量联合的
Keys
,它包含了要迭代的属性名的集合。 - 属性的结果类型。
2. 模块
TypeScript与ECMAScript 2015一样,任何包含顶级import
或者export
的文件都被当成一个模块。
模块使用模块加载器去导入其它的模块。 在运行时,模块加载器的作用是在执行此模块代码前去查找并执行这个模块的所有依赖。 大家最熟知的JavaScript模块加载器是服务于Node.js的CommonJS和服务于Web应用的Require.js。
导出
每个模块都可以有一个default
导出。 默认导出使用default
关键字标记;并且一个模块只能够有一个default
导出。
3.tsconfig配置文件
- compilerOptions: 编译设置
- files: 制定包含相对、绝对路径列表,优先级大于exclude
- include, exclude: 指定一个文件glob匹配模式列表
*
匹配0或多个字符(不包括目录分隔符)?
匹配一个任意字符(不包括目录分隔符)**/
递归匹配任意子目录
- typeRoots, types: 默认@types包会被包含,指定了typeRoots,只有指定的包才会被包含,types:只有被列出的包才会被包含。
自动引入只有在使用全局声明(相对于模块)时是重要的,如果你使用
import "foo"
语句,TypeScript仍然会查找node_modules
和node_modules/@types
文件夹来获取foo
包。
- 使用extends继承配置 配置文件里的相对路径在解析时相对于它所在的文件。
比如:
configs/base.json
:
{
"compilerOptions": {
"noImplicitAny": true,
"strictNullChecks": true
}
}
tsconfig.json
:
{
"extends": "./configs/base",
"files": [
"main.ts",
"supplemental.ts"
]
}
tsconfig.nostrictnull.json
:
{
"extends": "./tsconfig",
"compilerOptions": {
"strictNullChecks": false
}
}
4. 编译选项
编译选项
选项 | 类型 | 默认值 | 描述 | ||
---|---|---|---|---|---|
--allowJs | boolean | false | 允许编译javascript文件。 | ||
--allowSyntheticDefaultImports | boolean | module === "system" | 允许从没有设置默认导出的模块中默认导入。这并不影响代码的显示,仅为了类型检查。 | ||
--allowUnreachableCode | boolean | false | 不报告执行不到的代码错误。 | ||
--allowUnusedLabels | boolean | false | 不报告未使用的标签错误。 | ||
--alwaysStrict | boolean | false | 以严格模式解析并为每个源文件生成"use strict" 语句 | ||
--baseUrl | string | 解析非相对模块名的基准目录。查看模块解析文档了解详情。 | |||
--charset | string | "utf8" | 输入文件的字符集。 | ||
--checkJs | boolean | false | 在.js文件中报告错误。与--allowJs 配合使用。 | ||
--declaration -d | boolean | false | 生成相应的.d.ts 文件。 | ||
--declarationDir | string | 生成声明文件的输出路径。 | |||
--diagnostics | boolean | false | 显示诊断信息。 | ||
--disableSizeLimit | boolean | false | 禁用JavaScript工程体积大小的限制 | ||
--emitBOM | boolean | false | 在输出文件的开头加入BOM头(UTF-8 Byte Order Mark)。 | ||
--emitDecoratorMetadata [1] | boolean | false | 给源码里的装饰器声明加上设计类型元数据。查看issue #2577了解更多信息。 | ||
--experimentalDecorators [1] | boolean | false | 启用实验性的ES装饰器。 | ||
--forceConsistentCasingInFileNames | boolean | false | 禁止对同一个文件的不一致的引用。 | ||
--help -h | 打印帮助信息。 | ||||
--importHelpers | string | 从tslib 导入辅助工具函数(比如__extends ,__rest 等) | |||
--inlineSourceMap | boolean | false | 生成单个sourcemaps文件,而不是将每sourcemaps生成不同的文件。 | ||
--inlineSources | boolean | false | 将代码与sourcemaps生成到一个文件中,要求同时设置了--inlineSourceMap 或--sourceMap 属性。 | ||
--init | 初始化TypeScript项目并创建一个tsconfig.json 文件。 | ||||
--isolatedModules | boolean | false | 将每个文件作为单独的模块(与“ts.transpileModule”类似)。 | ||
--jsx | string | "Preserve" | 在.tsx 文件里支持JSX:"React" 或"Preserve" 。查看JSX。 | ||
--jsxFactory | string | "React.createElement" | 指定生成目标为react JSX时,使用的JSX工厂函数,比如React.createElement 或h 。 | ||
--lib | string[] | 编译过程中需要引入的库文件的列表。 可能的值为: ► ES5 ► ES6 ► ES2015 ► ES7 ► ES2016 ► ES2017 ► DOM ► DOM.Iterable ► WebWorker ► ScriptHost ► ES2015.Core ► ES2015.Collection ► ES2015.Generator ► ES2015.Iterable ► ES2015.Promise ► ES2015.Proxy ► ES2015.Reflect ► ES2015.Symbol ► ES2015.Symbol.WellKnown ► ES2016.Array.Include ► ES2017.object ► ES2017.SharedMemory ► ES2017.TypedArrays ► esnext.asynciterable 注意:如果--lib 没有指定默认注入的库的列表。默认注入的库为: ► 针对于--target ES5 :DOM,ES5,ScriptHost ► 针对于--target ES6 :DOM,ES6,DOM.Iterable,ScriptHost | |||
--listEmittedFiles | boolean | false | 打印出编译后生成文件的名字。 | ||
--listFiles | boolean | false | 编译过程中打印文件名。 | ||
--locale | string | (platform specific) | 显示错误信息时使用的语言,比如:en-us。 | ||
--mapRoot | string | 为调试器指定指定sourcemap文件的路径,而不是使用生成时的路径。当.map 文件是在运行时指定的,并不同于js 文件的地址时使用这个标记。指定的路径会嵌入到sourceMap 里告诉调试器到哪里去找它们。 | |||
--maxNodeModuleJsDepth | number | 0 | node_modules依赖的最大搜索深度并加载JavaScript文件。仅适用于--allowJs 。 | ||
--module -m | string | target === "ES6" ? "ES6" : "commonjs" | 指定生成哪个模块系统代码:"None" ,"CommonJS" ,"AMD" ,"System" ,"UMD" ,"ES6" 或"ES2015" 。 ► 只有"AMD" 和"System" 能和--outFile 一起使用。 ►"ES6" 和"ES2015" 可使用在目标输出为"ES5" 或更低的情况下。 | ||
--moduleResolution | string | `module === "AMD" | "System" | "ES6" ? "Classic" : "Node"` | 决定如何处理模块。或者是"Node" 对于Node.js/io.js,或者是"Classic" (默认)。查看模块解析了解详情。 |
--newLine | string | (platform specific) | 当生成文件时指定行结束符:"crlf" (windows)或"lf" (unix)。 | ||
--noEmit | boolean | false | 不生成输出文件。 | ||
--noEmitHelpers | boolean | false | 不在输出文件中生成用户自定义的帮助函数代码,如__extends 。 | ||
--noEmitOnError | boolean | false | 报错时不生成输出文件。 | ||
--noFallthroughCasesInSwitch | boolean | false | 报告switch语句的fallthrough错误。(即,不允许switch的case语句贯穿) | ||
--noImplicitAny | boolean | false | 在表达式和声明上有隐含的any 类型时报错。 | ||
--noImplicitReturns | boolean | false | 不是函数的所有返回路径都有返回值时报错。 | ||
--noImplicitThis | boolean | false | 当this 表达式的值为any 类型的时候,生成一个错误。 | ||
--noImplicitUseStrict | boolean | false | 模块输出中不包含"use strict" 指令。 | ||
--noLib | boolean | false | 不包含默认的库文件(lib.d.ts )。 | ||
--noResolve | boolean | false | 不把/// <reference``> 或模块导入的文件加到编译文件列表。 | ||
--noStrictGenericChecks | boolean | false | 禁用在函数类型里对泛型签名进行严格检查。 | ||
--noUnusedLocals | boolean | false | 若有未使用的局部变量则抛错。 | ||
--noUnusedParameters | boolean | false | 若有未使用的参数则抛错。 | ||
--out | string | 弃用。使用 --outFile 代替。 | |||
--outDir | string | 重定向输出目录。 | |||
--outFile | string | 将输出文件合并为一个文件。合并的顺序是根据传入编译器的文件顺序和///<reference``> 和import 的文件顺序决定的。查看输出文件顺序文件了解详情。 | |||
paths [2] | Object | 模块名到基于baseUrl 的路径映射的列表。查看模块解析文档了解详情。 | |||
--preserveConstEnums | boolean | false | 保留const 和enum 声明。查看const enums documentation了解详情。 | ||
--preserveSymlinks | boolean | false | 不把符号链接解析为其真实路径;将符号链接文件视为真正的文件。 | ||
--pretty [1] | boolean | false | 给错误和消息设置样式,使用颜色和上下文。 | ||
--project -p | string | 编译指定目录下的项目。这个目录应该包含一个tsconfig.json 文件来管理编译。查看tsconfig.json文档了解更多信息。 | |||
--reactNamespace | string | "React" | 当目标为生成"react" JSX时,指定createElement 和__spread 的调用对象 | ||
--removeComments | boolean | false | 删除所有注释,除了以/!* 开头的版权信息。 | ||
--rootDir | string | (common root directory is computed from the list of input files) | 仅用来控制输出的目录结构--outDir 。 | ||
rootDirs [2] | string[] | 根(root) 文件夹列表,表示运行时组合工程结构的内容。查看模块解析文档了解详情。 | |||
--skipDefaultLibCheck | boolean | false | 忽略库的默认声明文件的类型检查。 | ||
--skipLibCheck | boolean | false | 忽略所有的声明文件(*.d.ts )的类型检查。 | ||
--sourceMap | boolean | false | 生成相应的.map 文件。 | ||
--sourceRoot | string | 指定TypeScript源文件的路径,以便调试器定位。当TypeScript文件的位置是在运行时指定时使用此标记。路径信息会被加到sourceMap 里。 | |||
--strict | boolean | false | 启用所有严格类型检查选项。 启用--strict 相当于启用 --noImplicitAny , --noImplicitThis , --alwaysStrict ,--strictNullChecks 和--strictFunctionTypes 。 | ||
--strictFunctionTypes | boolean | false | 禁用函数参数双向协变检查。 | ||
--strictNullChecks | boolean | false | 在严格的null 检查模式下,null 和undefined 值不包含在任何类型里,只允许用它们自己和any 来赋值(有个例外,undefined 可以赋值到void )。 | ||
--stripInternal [1] | boolean | false | 不对具有/** @internal */ JSDoc注解的代码生成代码。 | ||
--suppressExcessPropertyErrors [1] | boolean | false | 阻止对对象字面量的额外属性检查。 | ||
--suppressImplicitAnyIndexErrors | boolean | false | 阻止--noImplicitAny 对缺少索引签名的索引对象报错。查看issue #1232了解详情。 | ||
--target -t | string | "ES3" | 指定ECMAScript目标版本"ES3" (默认),"ES5" ,"ES6" /"ES2015" ,"ES2016" ,"ES2017" 或"ESNext" 。 注意:"ESNext" 最新的生成目标列表为ES proposed features | ||
--traceResolution | boolean | false | 生成模块解析日志信息 | ||
--types | string[] | 要包含的类型声明文件名列表。查看@types,–typeRoots和–types章节了解详细信息。 | |||
--typeRoots | string[] | 要包含的类型声明文件路径列表。查看@types,–typeRoots和–types章节了解详细信息。 | |||
--version -v | 打印编译器版本号。 | ||||
--watch -w | 在监视模式下运行编译器。会监视输出文件,在它们改变时重新编译。 |
- [1] 这些选项是试验性的。
- [2] 这些选项只能在
tsconfig.json
里使用,不能在命令行使用。