- 有 3 种字面量类型:字符串字面量类型、数字字面量类型、布尔字面量类型
const specifiedStr: 'this is string' = 'this is string';
const specifiedNum: 1 = 1;
const specifiedBoolean: true = true;
type prefix = `#${string}`
const a: prefix = 'aaa'
const b: prefix = '#aaa'
type Direction = 'up' | 'down'
- let 定义变量会被推断成字面量的父类型,const 则会被推断成字面量类型(只针对于三种字面量类型)
let s1 = 'a'
const s2 = 'a'
- 对于对象类型,const 不生效,但可以使用断言
as const
,使其类型拓宽
interface Props {
name: 'musi'
}
interface Props {
name: 'musi' as const
}
interface Props {
name: 'musi',
id: 1
} as const
['musi' as const]