type常用用法
type words = (word: string) => string //type 定义函数类型1
type AddtionType={(a:number,b:number):number} //type 定义函数类型2 很像接口是不是
type methodType = 'GET' | 'POST' | 'get' | 'post' //定义字面量类型
//type定义基本数据类型
let a0: number = 23 type A = number //number本身是个类型 我用type A去给number起个别名 搞出下面这个东西出来 let a: A = 23
type定义对象数据类型
// 通常type是这样定义类型的 type PersonType = { name: string age: number } // 重点看下面这里 let p = { name: 'zs', age: 10, } type PersonType1 = typeof p //typeof 可以由一个普通对象来定义一个类型A出来,然后用这个类型A去约束其他的变量 let p1: PersonType = { name: 'lisi', age: 12, }
keyof 索引类型查询操作符(拿到类型[interface|type|class]的key|数组的索引)
// keyof 索引类型查询操作符(拿到对象的key|数组的索引) interface IPerson { name: string age: number gender: 'male' | 'female' } type PersonKeysType = keyof IPerson //得到interface接口的所有key集合组成一个type 类似于name|age|gender interface IGetValueByKeyFunc { (obj: IPerson, key: PersonKeysType): any } const getValueByKey: IGetValueByKeyFunc = (obj, key) => { return obj[key] } let person: IPerson = { name: 'zs', age: 10, gender: 'male' } console.log(getValueByKey(person, 'name'))
由type生成interface
interface IPerson { name: string age: number like: Array<string> } interface IPickedPerson extends Pick<IPerson, 'name' | 'like'> { } //生成新的接口 const p: IPickedPerson = { name: 'zs', like: ['a', 'b'] }
Partial|Required|Readonly|Pick
interface IPerson { name: string age: number gender: 'male' | 'female' } // ts自带Partial 将一个已知的类型(接口)每个属性都变为可选的:注意使用type关键字定义的 type PartialPerson2 = Partial<IPerson> type RequiredPerson3 = Required<IPerson> //ts内置 Required<type|interface|class> PartialPerson1是type类型 同样也可以传入接口 let requiredP: RequiredPerson3 = { name: 'zs', age: 10, gender: 'male' } type ReadOnlyPerson = Readonly<RequiredPerson3> //Readonly<type|interface|class> let readonlyP: ReadOnlyPerson = { name: 'zs', age: 10, gender: 'male' } type PickPerson = Pick<IPerson, 'name' | 'age'> //Pick<interface|type|class> 原来是必须|可选|可读 选出来的也是同样属性。 |属性分割表示可以选出多个 let pickPerson: PickPerson = { name: 'zs', age: 10 }
Exclude|Extract|NonNullable|ReturnType|InstanceType
//Exclude|Extract|NonNullable|ReturnType|InstanceType type E = Exclude<string | number | boolean, string | boolean> //Exclude<A,B> //把类型B从类型A中剔除 let e: E = 10 type E2 = Extract<string | number, string> //Extract<A,B> 从类型A中提取类型B let e2: E2 = '12' type E3 = NonNullable<string | number | null | undefined> let e3: E3 = null function getUserInfo(){ return {name:'zs',age:10} } type UserInfo=ReturnType<typeof getUserInfo> //拿到返回值类型 let userInfo: UserInfo={name:'lisi',age:10} class Person { name:string age:number constructor(name:string,age:number){ this.name=name this.age=age } } type P=InstanceType<typeof Person> let p:P=new Person('zs',10) console.log(p);