深入TypeScript类型

87 阅读1分钟

Record

Record<K, T> K代表键,T代表值

type User = { firstName: string, lastName: string }
const myData:Record<string, User> = { 
    "123-123-123" : { firstName: "John", lastName: "Doe" }, 
    "124-124-124" : { firstName: "Sarah", lastName: "Doe" }, 
    "125-125-125" : { firstName: "Jane", lastName: "Smith" } 
}
type User = { firstName: string, lastName: string } 
type Country = "uk" | "france" | "india"
const myData:Record<Country, User> = { 
    "uk" : { firstName: "John", lastName: "Doe" }, 
    "france" : { firstName: "Sarah", lastName: "Doe" }, 
    "india" : { firstName: "Jane", lastName: "Smith" } 
}

Omit

Omit<T, 联合类型> 去除,用于type类型定义去除不要的属性

type User = { 
    firstName: string;
    lastName: string;
    age: number;
    lastActive: number; 
} 

type UserNameOnly = Omit<User, "age" | "lastActive"> 
type UserNameAndActive = Omit<User, "age">

const userByName:UserNameOnly = { 
    firstName: "John", 
    lastName: "Doe", 
}; 
const userWithoutAge:UserNameAndActive = { 
    firstName: "John", 
    lastName: "Doe", 
    lastActive: -16302124725 
}

Pick

Pick<T, 联合类型> 选取一部分需要的属性重组一个类型

type User = { 
    firstName: string, 
    lastName: string, age: number 
} 
type UserAge = Pick<User, "age"> 
let age:UserAge = { age: 1534 }

Partial <T> 全部变成可选

Required<T> 全部变成必选

keyof  any 返回接口或type的联合类型

Parameters

定义函数参数组成一个元组。

const myFunction = (a: string, b: string) => { return a + b; }
type myType = Parameters<typeof myFunction> 
// Equivalent to a tuple type of: // type myType = [ a: string, b: string ]
let passArray:myType = [ 'hello ', 'world' ]
myFunction(...passArray);

ReturnType

将一个函数的返回值作为type。

function sendData(a: number, b: number) { 
    return { a: `${a}`, b: `${b}` }
}
type Data = ReturnType<typeof sendData> 
// The same as writing: 
// type Data = { 
    // a: string, 
    // b: string 
// }

NonNullable

从联合类型中去除null和undefined。

type myType = string | number | null | undefined 
type noNulls = NonNullable<myType>
// The same as writing: 
// type noNulls = string | number.

Exclude

从已有的联合类型中剔除一部分类型。

Exclude <T, U>   T extends U ? never : T

Exclude < 联合类型1, 联合类型2>

联合类型1的每一个元素 extends 联合类型2never : 当前元素

type myUnionType = "🍇" | "🍎" | "🫐" | "🍋" 
// This works! 
let lemon:myUnionType = "🍋" 
// This throws an error! Type '"🍋"' is not assignable to type '"🍇" | "🍎" | "🫐"'. 
let noLemonsPlease:Exclude<myUnionType, "🍋"> = "🍋"

Extract

只保留需要的联合类型。

Extract<T, U>  T extends U ? T : never

Extract< 联合类型1, 联合类型2>

联合类型1的每一个元素 extends 联合类型2 ?当前元素 : never

构造一个新的联合类型

type myUnionType = "🥒" | "🥔" | "🌶" | "🌽" 
let myFirstVariable:Extract<myUnionType, "🥒" | "🥔"> = "🥒" 
//  Type is "🥒" | "🥔"

更多知识学习见: fjolt.com/article/typ…