在 TypeScript 中,字面量不仅可以表示值,还可以表示类型,即所谓的字面量类型。
目前,TypeScript 支持 3 种字面量类型:字符串字面量类型、数字字面量类型、布尔字面量类型。
{let specifiedStr: 'this is string' = 'this is string';let specifiedNum: 1 = 1;let specifiedBoolean: true = true;}
{let specifiedStr: 'this is string' = 'this is string';let str: string = 'any string';specifiedStr = str; // ts(2322) 类型 '"string"' 不能赋值给类型 'this is string'str = specifiedStr; // ok}
type Direction = 'up' | 'down';function move(dir: Direction) {// ...}move('up'); // okmove('right'); // ts(2345) Argument of type '"right"' is not assignable to parameter of type 'Direction'
const 类型推断,会推断为字面量类型
{const str = 'this is string'; // str: 'this is string'const num = 1; // num: 1const bool = true; // bool: true}
Literal Widening
所有通过 let 或 var 定义的变量、函数的形参、对象的非只读属性,如果满足指定了**初始值**且未显式添加类型注解的条件,那么它们推断出来的类型就是指定的初始值字面量类型拓宽后的类型,这就是字面量类型拓宽。
{let str = 'this is string'; // 类型是 stringlet strFun = (str = 'this is string') => str; // 类型是 (str?: string) => string;const specifiedStr = 'this is string'; // 类型是 'this is string'let str2 = specifiedStr; // 类型是 'string'let strFun2 = (str = specifiedStr) => str; // 类型是 (str?: string) => string;}
如果添加显示类型注解,则不触发类型拓宽。
{const specifiedStr: 'this is string' = 'this is string'; // 类型是 '"this is string"'let str2 = specifiedStr; // 即便使用 let 定义,类型是 'this is string'}
Type Narrowing
在 TypeScript 中,我们可以通过某些操作将变量的类型由一个较为宽泛的集合缩小到相对较小、较明确的集合,这就是 “Type Narrowing”。
{let func = (anything: any) => {if (typeof anything === 'string') {return anything; // 类型是 string} else if (typeof anything === 'number') {return anything; // 类型是 number}};}
