学习TypeScrip11---类型推论|类型别名

61 阅读1分钟

什么是类型推论

let str = 'xxx'
  1. 我声明了一个变量但是没有定义类型

TypeScript会在没有明确的指定类型的时候推测出一个类型,这就是类型推论

推断出来的类型,不能够再赋值给别的类型

  1. 如果你声明变量没有定义类型也没有赋值 这时候TS会推断成any类型可以进行任何操作

 类型别名

type 关键字(可以给一个类型定义一个名字)多用于复合类型

定义类型别名

type str = string

let s: str = '我下'

console.log(s)  // '我下'

定义函数别名

type str = () => string

let s: str = () => 'xxx'

console.log(s)

定义联合类型别名

type str = string | number

let s: str = 123

let s2: str = '123'

console.log(s, s2)

定义值的别名

type value = boolean | 0 | '213'

let s: value = true
// 变量s的值 只能是上面value定义的值

type 和 interface 还是一些区别的 虽然都可以定义类型

  1. interface可以继承 type只能通过 & 交叉类型合并
  2. type可以定义 联合类型,可以使用一些操作符 interface不可以
  3. 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 unknow ? 1 : 0 //1
type a = 1 extends never ? 1 : 0 //0

image.png