Partial(可选)

将类型中的字段全部转为可选类型。

  1. interface Props{
  2. age: number;
  3. name: string;
  4. }
  5. type props2 = Partial<Props>
  6. // {
  7. // age?: number
  8. // name: string
  9. // }

Required(必填)

将类型中的字段全部转为必填类型。

interface Props{
  age?: number;
  name: string;
}
type props2 = Required<Props>

// {
//   age: number
//   name: string
// }

Pick(过滤 | 挑选)

将类型中的字段全部转为只读类型。

interface Props{
  age: number;
  name: string;
}
type Demo = Pick<Props, 'age'>
// type Demo = { age: number }

Readonly(只读)

将类型中的字段全部转为只读类型。

interface Props{
  age: number;
  name: string;
}
type props2 = Readonly<Props>

// {
//   readonly age: number;
//   readonly name: string;
// }

Record(记录 | 映射)

将类型的所有属性,映射到另一个类型上,并创建一个新类型。

interface Props{
  age: number;
  name: string;
}
type Animal = 'cat' | 'dog';

type props2 = Record<Animal, Props>

// {
//   cat: {
//    age: number;
//    name: string;
//   },
//   dog: {
//    age: number;
//    name: string;
//   }
// }

Exclude(排除)

参数1,源类型;
参数2,需要排除的值;

type AB = 'a' | 'b'
type BC = 'b' | 'c'
type Demo = Exclude<AB, BC> // => type Demo = 'a'

Extract(反排除)

结果和Exclude相反。

type AB = 'a' | 'b'
type BC = 'b' | 'c'
type Demo = Exclude<AB, BC> // => type Demo = 'b'

Omit(反向过滤,反向Pick)

反向Pick,删除泛型A中可匹配的key

// 源代码
export type Omit<A, B extends keyof A> = Pick<A, Exclude<keyof A, B>>

示例:

interface Props{
  age: number;
  name: string;
  color: string;
}
type Demo = Omit<Props, 'age'>    
// type Demo = { name: string; color: string }

ReturnType(返回类型)

获取函数类型的返回类型。

interface Props{
  age: number;
  name: string;
}
type getUrl = (url: string) => Props;
type Demo = ReturnType<getUrl> // type Demo = Props;

InstanceType

获取构造函数函数类型的返回类型,有些类似 ConstructorParameters。

type E = InstanceType<ErrorConstructor>; // type F = Error
type F = InstanceType<FunctionConstructor>; // type F = Function

Parameters(函数参数)

用于获得当前函数参数类型,组成的数组。

type A = Parameters<() => void>; // []
type B = Parameters<typeof Array.isArray>; // [any]
type C = Parameters<typeof parseInt>; // [string, (number | undefined)?]
type D = Parameters<typeof Math.max>; // number[]

type getUrl = (url: string, options: IProps) => string;
type Demo = Parameters<getUrl>;
// type Demo = [url: string, options: IProps];

ConstructorParameters

用于获取当前构造函数,所有参数的类型,组成的数组。如果不是构造函数返回 never。

type A = ConstructorParameters<ErrorConstructor>; // [(string | undefined)?]
type B = ConstructorParameters<FunctionConstructor>; // string[]
type C = ConstructorParameters<RegExpConstructor>; // [string, (string | undefined)?]