1. 函数上声明返回值类型
const userInfoJson = require('./mock/user-info.json') interface Response<T> { data: { module: T; resultCode?: any; } } interface UserInfo { userId: string; userName?: string; loginEmail?: string; loginPhoneNo?: string; } export function getUserInfo(param= {}): Promise<Response<UserInfo>> { return Promise.resolve(userInfoJson) }
// 也可以把 T 泛型(对应的字段类型)声明在函数上面,适应于响应字段较少的场景
export function getUserInfo2(param= {}): Promise<Response<{ userid: number, userName?: string }>> { return Promise.resolve(userInfoJson) }
2. 常量数组声明作为类型
const _STATUS = [ _STATUS_LOGIN, _STATUS_INIT, _STATUS_PENDING, _STATUS_NORMAL, _STATUS_FROZEN, _STATUS_DISABLED, ] as const; interface StatusIProps { userStatus: typeof _STATUS[number]; }
3. Partial
Partial 作用是将传入的属性变为可选项。适用于对类型结构不明确的情况。它使用了两个关键字:keyof、in
type Person = { name: string; age: number; height: number; } type PartialPerson = Partial<Person>; // PartialPerson 的类型为 {name?: string; age?: number; height?: number;}
keyof 可以用来取得接口的所有 key 值:
type Person = { name: string; age: number; height: number; } type T = keyof Person // T 类型为: "name" | "age" | "number"
in关键字可以遍历枚举类型,:
type Person = "name" | "age" | "number" type Obj = { [p in Person]: any } // Obj 的类型为: { name: any, age: any, number: any }
4. Pick<Type, Keys>
从 Type类型中挑选部分属性 Keys 来构造新的类型。它的声明形式如下:
/** * From T, pick a set of properties whose keys are in the union K */ type Pick<T, K extends keyof T> = { [P in K]: T[P]; };
type Person = { name: string; age: number; height: number; } // 使用Pick从Person类型中挑出来了name和age属性的类型,新的类型中只包含这两个属性。 const person: Pick<Person, "name" | "age"> = { name: "zhangsan", age: 18 }
5. Omit<Type, Keys>
Omit 允许从一个对象中剔除若干个属性,剩下的就是需要的新类型。
type Person = { name: string; age: number; height: number; } // 使用Omit从Person类型中剔除了 age 和 height 属性,只剩下 name 属性。 const person: Omit<Person, "age" | "height"> = { name: "zhangsan"; }
Omit 结合 & 符用法
interface WithdrawalTypes { componentType: string, propsData: { value: any, label: string } } // 剔除WithdrawalTypes中propsData的 value属性,留下的 label 属性和 新声明的 value 属性组成新的类型 type IProps = Omit<WithdrawalTypes['propsData'], 'value'> & { value: { [key in 'userId' | 'userName' | 'loginEmail'] : string } } // 取值代码实例 const { propsData: data }: { propsData: IProps } = props <div {...data}></div>
参考:https://www.51cto.com/article/707434.html
标签:TypeScript,name,实用工具,number,Person,实例,type,age,string From: https://www.cnblogs.com/xuqichun/p/17070037.html