类型推论 | 类型别名
类型推论
const s = 'mk' // string
const b = true // boolean
const n = 1 // number
...
类型别名
type 关键字(可以给一个类型定义一个名字)多用于复合类型
定义类型别名
type str = string
const s: str = 'mk'
定义函数别名
type str = () => string
const s: str = () => 'mk'
定义联合类型别名
type str = string | number
const s: str = 'mk'
const s2: str = 1
定义值的别名
type str = boolean | 0 | 'mk'
const s: str = true // 变量s的值 只能是上面value定义的值
type 和 interface 还是一些区别的 虽然都可以定义类型
- interface可以继承 type 只能通过 & 交叉类型合并
- type 可以定义 联合类型 和 可以使用一些操作符 interface不行
- interface 遇到重名的会合并 type 不行
type高级用法
左边的值会作为右边值的子类型遵循图中上下的包含关系
type a = 1 extends number ? 1 : 0 //1
type a = 1 extends Number ? 1 : 0 //1
type a = 1 extends Object ? 1 : 0 //1
type a = 1 extends any ? 1 : 0 //1
type a = 1 extends unknown ? 1 : 0 //1
type a = 1 extends never ? 1 : 0 //0
unknown any
object
Number String Boolean
number string boolean
1 'mk' true
never