北京时间7月12日,TypeScript Program Manager Daniel Rosenwasser在Developer Tools Blogs中宣布了TypeScript 2.0 Beta的到来。其所包含的新特性和之前Anders Hejlsberg在微软Build大会上所分享的基本一致,首当其冲的便是非空类型。
非空类型
null
和undefined
是JavaScript漏洞中最为常见的两个来源。在TypeScript 2.0中,新提供了一个名为strictNullChecks
的编译器标识,由此,一个类型即丧失了为null
或undefined
的能力,用Daniel的话来讲就是,“string just means string and number means number”。
Example:
// Compiled with --strictNullChecks
let x: number;
let y: number | undefined;
let z: number | null | undefined;
x = 1; // Ok
y = 1; // Ok
z = 1; // Ok
x = undefined; // Error
y = undefined; // Ok
z = undefined; // Ok
x = null; // Error
y = null; // Error
z = null; // Ok
x = y; // Error
x = z; // Error
y = x; // Ok
y = z; // Error
z = x; // Ok
z = y; // Ok
基于控制流的类型分析
在之前的几个版本中,TypeScript对于类型分析方面并没有实质性的增强,而在2.0中,基于控制流的类型分析在很大程度上提高了TypeScript在编写类型的代码体验。“在2.0中,我们可以使用控制流分析来更好地理解在某一个指定位置应该如何设置一个类型。”例如:
/**
* @param recipients An array of recipients, or a comma-separated list of recipients.
* @param body Primary content of the message.
*/
function sendMessage(recipients: string | string[], body: string) {
if (typeof recipients === "string") {
recipients = recipients.split(",");
}
// TypeScript knows that 'recipients' is a 'string[]' here.
recipients = recipients.filter(isValidAddress);
for (let r of recipients) {
// ...
}
}
关于TypeScript 2.0的更多新特性,可直接查阅TypeScript Wiki - “What’s new in TypeScript”。