类型别名与接口的区别
1. TS 4.2版本以前,type 经过处理后可能不会出现在报错信息中;interface 会一直出现在报错信息中心
2. interface 声明合并
3. interface只能声明对象的类型,不能给基础类型重命名
4. 当类型系统中,使用了interface 名称后,interface 名称总会出现在报错信息中
字面量类型
字符串、布尔值、数字都可以作为字面量类型
type test = 1 | true | 'name'
对于一个没有类型声明的对象,如 { a: "a", b: 0},属性 a 的类型不会被TS认定为字面量类型 "a"。但是,可以通过 { a: "a", b: 0} as const 或者 { a: "a", b: 0 as 0} 将其类型变更为字面量类型。
// @errors: 2345
declare function handleRequest(url: string, method: "GET" | "POST"): void
// ---cut---
// Argument of type 'string' is not assignable to parameter of type '"GET" | "POST"'.const req = { url: "https://example.com", method: "GET" };
handleRequest(req.url, req.method);
方法一:
// Change 1:
const req = { url: "https://example.com", method: "GET" as "GET" };
// Change 2
handleRequest(req.url, req.method as "GET");
方法二:// Change 3
const req = { url: "https://example.com", method: "GET" } as const;
handleRequest(req.url, req.method);
null和undefined
被认为是 any 类型,容易导致 bug。可以通过设置 strictNullChecks 属性来检查。
! 符号等同于类型推断 x 非 null 或 undefined。
function liveDangerously(x?: number | null) { // No error console.log(x!.toFixed());}
枚举类型
枚举类型会侵入JS运行时