[官方] TypeScript 2.7 发布

时间:2021-1-8 作者:admin

{
0: number;
1: string;
length: 2; // using the numeric literal type ‘2’
}

Note that this is a breaking change. If you need to resort to the original behavior in which tuples only enforce a minimum size, you can use a similar declaration that does not explicitly define a `length` property, falling back to `number`.

interface MinimumNumStrTuple extends Array<number | string> {
0: number;
1: string;
}

## `in` operator narrowing and accurate `instanceof`

TypeScript 2.7 brings two new changes to type narrowing – the ability to get a more specific type for a value by running certain types of checks called “type guards”.

First, the `instanceof` operator is now leverages the inheritance chain instead of

relying on structural compatibility, more accurately reflecting whether how `instanceof` may behave at runtime. This can help avoid certain complex issues when `instanceof` narrows from structurally similar (but unrelated) types.

Second, thanks to GitHub user [IdeaHunter](https://link.funteas.com?target=https%3A%2F%2Fgithub.com%2Fideahunter), the `in` operator [now acts as a type guard](https://link.funteas.com?target=https%3A%2F%2Fgithub.com%2FMicrosoft%2FTypeScript%2Fpull%2F15256), narrowing out types that don’t explicitly declare properties of a given name.

interface A { a: number };
interface B { b: string };

function foo(x: A | B) {
if (“a” in x) {
return x.a;
}
return x.b;
}

## Smarter object literal inference

There are certain patterns in JavaScript where users will omit properties so that all uses of those properties are effectively `undefined`.

let foo = someTest ? { value: 42 } : {};

TypeScript used seek the best common supertype between `{ value: number }` and `{}`, ending up with `{}`. While being technically correct, this wasn’t very useful.

Starting with version 2.7, TypeScript now “normalizes” each object literal’s type to account for every property, inserting an optional property of type `undefined` on each object type, and unioning them together.

From the above example, the new type of `foo` would be `{ foo: number } | { foo?: undefined }`. Combined with the ways TypeScript can narrow, this lets us write expressive code that TypeScript can still understand. As another example, take the following:

// Has type
// | { a: boolean, aData: number, b?: undefined }
// | { b: boolean, bData: string, a?: undefined }
let bar = Math.random()

声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。