TypeScript类型声明
TypeScript中提供了一些基本类型(number、string、boolean、Symbol、Array、object、enum、void、null/undefined、any),但是有些时候需要灵活地类型,这就需要自定义一些类型或者叫类型声明。
类型别名:type
接口:interface
两者大多数场景是通用的,但是type可以定义numer、string、
interface
可以扩展 type
,type
也可以扩展为 interface
,但两者实现扩展的方式不同。
interface
是通过extends
来实现type
是通过&
来实现
// interface 扩展
interface interface A { a: string }
interface B extends A { b: number }
const obj:B = { a: `zhangsan`, b: 7 }
// type 扩展
type type C = { a: string }
type D = C & { b: number }
const obj1:D = { a: `zhangsan`, b: 7 }
// interface 扩展为
Type type E = { a: string }
interface F extends E { b: number }
const obj2:F = { a: `zhangsan`, b: 7 }
// type 扩展为 interface
interface G { a: string }
type H = G & {b: number}
const obj3:H = { a: `zhangsan`, b: 7 }
Partial
部分的/局部的/不完全的
类型声明(源码)
示例
Record

示例
注意:K extends keyof any 其类型可以是string、number、symbol
Pick
从 T 中,选择一组键在并集 K 中的属性。实际就是说在原有的类型 T 上 筛选出想要的全部或极个别的属性和类型
类型声明(源码)
示例
Omit
作用与Pick相反,Omit是排除一个字段,剩下的所有
类型声明(源码)
示例