前文链接
原文链接
早些时间就听说了lookup types
但是一直不知道他究竟是个什么,2.1版本我终于要知道他的庐山真面目了。
keyof
and Lookup Types
keyof T
生成的type 是 string
的subtype
lookup type:一种看上去很像属性访问,但是[]
内写入一个type
称为lookup type。
interface Person {
name: string;
age: number;
location: string;
}
type P2 = Person["name" | "age"]; // string | number
Mapped Types
通过联合类型来计算一个新对象类型的属性
type Partial<T> = {
[P in keyof T]?: T[P];
};
type PartialPerson = Partial<Person>;
Object Spread and Rest(支持对象扩展运算符)
let copy = { ...original };
Downlevel Async Functions(更低版本js标准的async函数支持)
ts2.1支持async
function在ES3、ES5的运行时
需要进行配置
{
"compilerOptions": {
"lib": ["dom", "es2015.promise", "es5"]
}
}
Support for external helpers library (tslib
)
需要配合--importHelpers
使用
为什么需要使用该配置?
ts在Emit一个js文件时,会进行js的编译,将语法转换为一些poli fill 辅助代码。但是在每个独立文件中都保存这些可复用的代码会增大文件体积,所以将这些生成的辅助代码放在tslib
中保存,并使用import
在使用进行导入,这样还能在构建时进行treeshaking
Support for--target ES2016
,--target ES2017
and--target ESNext
Better inference for literal types(更优秀的字面量推断)
const不搭配type annotation会wide 变量类型
const c1 = "hello"; // Widening type "hello"
let v1 = c1; // v1 Type string
const c2: "hello" = "hello"; // Type "hello"
let v2 = c2; // v2 Type "hello"
Configuration inheritance配置继承
- 在
tsconfig.json
使用extends
关键字 extends
文件中的重新配置的内容会覆盖父级或更高级的内容- 不能使得继承关系形成一个环状关系
- 优先使用更高级的路径配置关系
//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
}
}
New--alwaysStrict
Ensure ‘use strict’ is always emitted,在生成的js顶部增加use strict
来保证js的严格模式