any => unknown => never
- any: 没有类型校验,当开发者不希望 ts在编译时做 typechecking, 而且希望 ts 相信这行代码是 ok的
- known: known 是 is safer than any. 当值是 known, 不允许对它做任何操作,看代码:
function f1(a: any) {
a.b(); // ok 👌 , any 允许这么做,就算 a 可能只是一个数字,它并没有 b 方法
}
function f2(a: unknown) {
a.b(); // 报错 ❌,使用 unknow的方法,必须先提前校验它,如何校验?
}
如何校验? 可以使用 typeof 或者 比较之后,才可以使用,才不会报错!!
if (maybe === true) {
// TypeScript knows that maybe is a boolean now
const aBoolean: boolean = maybe;
// So, it cannot be a string
const aString: string = maybe;
Type 'boolean' is not assignable to type 'string'.
}
if (typeof maybe === "string") {
// TypeScript knows that maybe is a string
const aString: string = maybe;
// So, it cannot be a boolean
const aBoolean: boolean = maybe;
Type 'string' is not assignable to type 'boolean'.
}
- never 类型是指,这个类型永远不可能,比如 一个值,既是 number 类型,又是 string类型
- 一般,never 在用于终止程序运行和抛出异常的 function 中
function fail(msg: string): never {
throw new Error(msg);
}