Open laclys opened 3 years ago
我们知道自动类型推导,只有收窄是安全的 eg:
function foo(arg: unknown) { if (typeof arg === "string") { // We know 'arg' is a string now. console.log(arg.toUpperCase()); } }
但是在4.4之前如果`我们将这个判定赋值给一个变量,再用到 if 分支里,就无法正常收窄类型了`
eg:
```typescript
function foo(arg: unknown) {
const argIsString = typeof arg === "string";
if (argIsString) {
console.log(arg.toUpperCase());
// ~~~~~~~~~~~
// Error! Property 'toUpperCase' does not exist on type 'unknown'.
}
}
除此之外不仅是单一的判断,Typescript 4.4 还支持复合类型推导。4.4 支持了大部分符合直觉的推导非常方便
interface Colors {
[sym: symbol]: number;
}
const red = Symbol("red");
const green = Symbol("green");
const blue = Symbol("blue");
let colors: Colors = {};
colors[red] = 255; // Assignment of a number is allowed
let redVal = colors[red]; // 'redVal' has the type 'number'
colors[blue] = "da ba dee"; // Error: Type 'string' is not assignable to type 'number'.
对于特定的字符串模版也支持类型匹配,比如希望以 data- 开头的下标是一种独立类型
interface Options {
width?: number;
height?: number;
}
let a: Options = {
width: 100,
height: 100,
"data-blah": true, // Error! 'data-blah' wasn't declared in 'Options'.
};
interface OptionsWithDataProps extends Options {
// Permit any property starting with 'data-'.
[optName: `data-${string}`]: unknown;
}
let b: OptionsWithDataProps = {
width: 100,
height: 100,
"data-blah": true, // Works!
"unknown-property": true, // Error! 'unknown-property' wasn't declared in 'OptionsWithDataProps'.
};
4.0 元组元素标签
可变元组
可以在函数组合中使用可变元组约束高阶函数入参和返回值的类型,比如对 JavaScript 内置 bind 方法更好地进行类型检测支持
4.1 模板字面量
type RoutePath<P extends string, N extends string> =
user/${P}/${N}/
type a = RoutePath<'123', 'Lac'> // "user/123/Lac/"4.1 映射类型键名重新映射
这个还没有测试,如果使用
Redux-saga
管理effect副作用yield
这块要注意4.3增加了关键字 overrride