TypeScript 4.1

TypeScript 4.1

模版字面量类型

使用字符串字面量类型能够表示仅接受特定字符串参数的函数和 API。

```ts twoslash function setVerticalAlignment(location: ‘top’ | ‘middle’ | ‘bottom’) { // … }

setVerticalAlignment(‘middel’); // ^^^^^^^^ // Argument of type ‘“middel”‘ is not assignable to parameter of type ‘“top” | “middle” | “bottom”‘.

使用字符串字面量类型的好处是它能够对字符串进行拼写检查。此外,字符串字面量还能用于映射类型中的属性名。从这个意义上来讲,它们可被当作构件使用。```tstype Options = {    [K in        | 'noImplicitAny'        | 'strictNullChecks'        | 'strictFunctionTypes']?: boolean;};// same as//   type Options = {//       noImplicitAny?: boolean,//       strictNullChecks?: boolean,//       strictFunctionTypes?: boolean//   };

还有一处字符串字面量类型可被当作构件使用,那就是在构造其它字符串字面量类型时。

这也是 TypeScript 4.1 支持模版字面量类型的原因。 它的语法与JavaScript 中的模版字面量的语法是一致的,但是是用在表示类型的位置上。 当将其与具体类型结合使用时,它会将字符串拼接并产生一个新的字符串字面量类型。

```ts twoslash type World = ‘world’;

type Greeting = hello ${World}; // ^^^^^^^^^ // “hello world”

如果在替换的位置上使用了联合类型会怎么样呢?它将生成由各个联合类型成员所表示的字符串字面量类型的联合。```ts twoslashtype Color = 'red' | 'blue';type Quantity = 'one' | 'two';type SeussFish = `${Quantity | Color} fish`;//   ^^^^^^^^^//   "one fish" | "two fish" | "red fish" | "blue fish"

除此之外,我们也可以在其它场景中应用它。 例如,有些 UI 组件库提供了指定垂直和水平对齐的 API,通常会使用类似于"bottom-right"的字符串来同时指定。 在垂直对齐的选项"top","middle"和"bottom",以及水平对齐的选项"left","center"和"right"之间,共有 9 种可能的字符串,前者选项之一与后者选项之一之间使用短横线连接。

```ts twoslash type VerticalAlignment = ‘top’ | ‘middle’ | ‘bottom’; type HorizontalAlignment = ‘left’ | ‘center’ | ‘right’;

// Takes // | “top-left” | “top-center” | “top-right” // | “middle-left” | “middle-center” | “middle-right” // | “bottom-left” | “bottom-center” | “bottom-right”

declare function setAlignment( value: ${VerticalAlignment}-${HorizontalAlignment} ): void;

setAlignment(‘top-left’); // works! setAlignment(‘top-middel’); // error! setAlignment(‘top-pot’); // error! but good doughnuts if you’re ever in Seattle

这样的例子还有很多,但它仍只是小例子而已,因为我们可以直接写出所有可能的值。实际上,对于 9 个字符串来讲还算可以;但是如果需要大量的字符串,你就得考虑如何去自动生成(或者简单地使用`string`)。有些值实际上是来自于动态创建的字符串字面量。例如,假设 `makeWatchedObject` API 接收一个对象,并生成一个几乎等同的对象,但是带有一个新的`on`方法来检测属性的变化。```tslet person = makeWatchedObject({    firstName: 'Homer',    age: 42,    location: 'Springfield',});person.on('firstNameChanged', () => {    console.log(`firstName was changed!`);});

注意,on监听的是"firstNameChanged"事件,而非仅仅是"firstName"。 那么我们如何定义类型?

`ts twslash type PropEventSource<​T> = { on(eventName:${string & keyof T}Changed, callback: () => void): void; };

/// Create a “watched object” with an ‘on’ method /// so that you can watch for changes to properties. declare function makeWatchedObject(obj: T): T & PropEventSource;

这样做的话,如果传入了错误的属性会产生一个错误!```ts twoslashtype PropEventSource<​T> = {    on(eventName: `${string & keyof T}Changed`, callback: () => void): void;};declare function makeWatchedObject<​T>(obj: T): T & PropEventSource<​T>;let person = makeWatchedObject({    firstName: 'Homer',    age: 42,    location: 'Springfield',});// error!person.on('firstName', () => {});// error!person.on('frstNameChanged', () => {});

我们还可以在模版字面量上做一些其它的事情:可以从替换的位置来推断类型。 我们将上面的例子改写成泛型,由eventName字符串来推断关联的属性名。

`ts twoslash type PropEventSource<​T> = { on<​K extends string & keyof T>( eventName:${K}Changed, callback: (newValue: T[K]) => void ): void; };

declare function makeWatchedObject(obj: T): T & PropEventSource;

let person = makeWatchedObject({ firstName: ‘Homer’, age: 42, location: ‘Springfield’, });

// works! ‘newName’ is typed as ‘string’ person.on(‘firstNameChanged’, (newName) => { // ‘newName’ has the type of ‘firstName’ console.log(new name is ${newName.toUpperCase()}); });

// works! ‘newAge’ is typed as ‘number’ person.on(‘ageChanged’, (newAge) => { if (newAge < 0) { console.log(‘warning! negative age’); } });

这里我们将`on`定义为泛型方法。当用户使用`"firstNameChanged'`来调用该方法,TypeScript 会尝试去推断出`K`所表示的类型。为此,它尝试将`K`与`"Changed"`之前的内容进行匹配并推断出`"firstName"`。一旦 TypeScript 得到了结果,`on`方法就能够从原对象上获取`firstName`的类型,此例中是`string`。类似地,当使用`"ageChanged"`调用时,它会找到属性`age`的类型为`number`。类型推断可以用不同的方式组合,常见的是解构字符串,再使用其它方式重新构造它们。实际上,为了便于修改字符串字面量类型,我们引入了一些新的工具类型来修改字符大小写。```ts twoslashtype EnthusiasticGreeting<​T extends string> = `${Uppercase<​T>}`;type HELLO = EnthusiasticGreeting<'hello'>;//   ^^^^^//   "HELLO"

新的类型别名为Uppercase,Lowercase,Capitalize和Uncapitalize。 前两个会转换字符串中的所有字符,而后面两个只转换字符串的首字母。

更多详情,查看原 PR以及正在进行中的切换类型别名助手的 PR.

在映射类型中更改映射的键

让我们先回顾一下,映射类型可以使用任意的键来创建新的对象类型。

type Options = {    [K in        | 'noImplicitAny'        | 'strictNullChecks'        | 'strictFunctionTypes']?: boolean;};// same as//   type Options = {//       noImplicitAny?: boolean,//       strictNullChecks?: boolean,//       strictFunctionTypes?: boolean//   };

或者,基于任意的对象类型来创建新的对象类型。

/// 'Partial<​T>' 等同于 'T',只是把每个属性标记为可选的。type Partial<​T> = {    [K in keyof T]?: T[K];};

到目前为止,映射类型只能使用提供给它的键来创建新的对象类型;然而,很多时候我们想要创建新的键,或者过滤掉某些键。

这就是 TypeScript 4.1 允许更改映射类型中的键的原因。它使用了新的as语句。

type MappedTypeWithNewKeys<​T> = {    [K in keyof T as NewKeyType]: T[K];    //            ^^^^^^^^^^^^^    //            这里是新的语法!};

通过as语句,你可以利用例如模版字面量类型,并基于原属性名来轻松地创建新属性名。

`ts twoslash type Getters<​T> = { [K in keyof T asget${Capitalize}]: () => T[K]; };

interface Person { name: string; age: number; location: string; }

type LazyPerson = Getters; // type LazyPerson = { // getName: () => string; // getAge: () => number; // getLocation: () => string; // }

此外,你可以巧用`never`类型来过滤掉某些键。也就是说,在某些情况下你不必使用`Omit`工具类型。```ts twoslash// 删除 'kind' 属性type RemoveKindField<​T> = {    [K in keyof T as Exclude<​K, 'kind'>]: T[K];};interface Circle {    kind: 'circle';    radius: number;}type KindlessCircle = RemoveKindField<​Circle>;type RemoveKindField<​T> = {    [K in keyof T as Exclude<​K, 'kind'>]: T[K];};interface Circle {    kind: 'circle';    radius: number;}type KindlessCircle = RemoveKindField<​Circle>;// type KindlessCircle = {//     radius: number;// }

更多详情,请参考PR。

递归的有条件类型

在 JavaScript 中较为常见的是,一个函数能够以任意的层级来展平(flatten)并构建容器类型。 例如,可以拿Promise实例对象上的.then()方法来举例。 .then(...)方法能够拆解每一个Promise,直到它找到一个非Promise的值,然后将该值传递给回调函数。 Array上也存在一个相对较新的flat方法,它接收一个表示深度的参数,并以此来决定展平操作的层数。

在过去,我们无法使用 TypeScript 类型系统来表达上述例子。 虽然也存在一些 hack,但基本上都不切合实际。

TypeScript 4.1 取消了对有条件类型的一些限制 - 因此它现在可以表达上述类型。 在 TypeScript 4.1 中,允许在有条件类型的分支中立即引用该有条件类型自身,这就使得编写递归的类型别名变得更加容易。 例如,我们想定义一个类型来获取嵌套数组中的元素类型,可以定义如下的deepFlatten类型。

type ElementType<​T> = T extends ReadonlyArray<​infer U> ? ElementType<​U> : T;function deepFlatten<​T extends readonly unknown[]>(x: T): ElementType<​T>[] {    throw 'not implemented';}// All of these return the type 'number[]':deepFlatten([1, 2, 3]);deepFlatten([[1], [2, 3]]);deepFlatten([[1], [[2]], [[[3]]]]);

类似地,在 TypeScript 4.1 中我们可以定义Awaited类型来拆解Promise。

type Awaited<​T> = T extends PromiseLike<​infer U> ? Awaited<​U> : T;/// 类似于 `promise.then(...)`,但是类型更准确declare function customThen<​T, U>(    p: Promise<​T>,    onFulfilled: (value: Awaited<​T>) => U): Promise<​Awaited<​U>>;

一定要注意,虽然这些递归类型很强大,但要有节制地使用它。

首先,这些类型能做的更多,但也会增加类型检查的耗时。 尝试为考拉兹猜想或斐波那契数列建模是一件有趣的事儿,但请不要在 npm 上发布带有它们的.d.ts文件。

除了计算量大之外,这些类型还可能会达到内置的递归深度限制。 如果到达了递归深度限制,则会产生编译错误。 通常来讲,最好不要去定义这样的类型。

更多详情,请参考PR.

索引访问类型检查(--noUncheckedIndexedAccess)

TypeScript 支持一个叫做索引签名的功能。 索引签名用于告诉类型系统,用户可以访问任意名称的属性。

```ts twoslash interface Options { path: string; permissions: number;

// 额外的属性可以被这个签名捕获[propName: string]: string | number;

}

function checkOptions(opts: Options) { opts.path; // string opts.permissions; // number

// 以下都是允许的// 它们的类型为 'string | number'opts.yadda.toString();opts['foo bar baz'].toString();opts[Math.random()].toString();

}