必须知道的Typescript实用类型

2023-04-061167次阅读TypeScript

Typescript中的实用类型是一些预定义的泛型类型,可用于操作或创建其他新类型。这些类型在所有Typescript项目中都是全局可用的,因此您不需要添加任何依赖项即可实现这些功能。

Partial

Partial用于将一个接口的所有属性设置为可选状态

interface Person {
  name: string;
  age: number;
  email: string;
}

// Define a new type called 'PartialPerson' that is a partial version of 'Person'
type PartialPerson = Partial<Person>;

// Same as:
// interface Person {
//   name?: string | undefined;
//   age?: number | undefined;
//   email?: string | undefined;
// }

Required

Required 的作用刚好与  Partial 相反,就是将接口中所有可选的属性改为必须的

interface Person {
 name?: string | undefined;
 age?: number | undefined;
 email?: string | undefined;
}

// Define a new type called 'RequiredPerson' that is a required version of 'Person'
type RequiredPerson = Required<Person>;

// Same as:
// interface Person {
//   name: string;
//   age: number;
//   email: string;
// }

Omit

Omit从现有类型创建新类型,但是会删除一些属性。

interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

type UserWithoutEmail = Omit<User, 'email'>;

// same as: 
// interface Person {
//   id: string;
//   name: string;
//   age: number;
// }

还可以传多个参数

interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

type UserWithoutEmailAndName = Omit<User, 'email' | 'name'>;

// same as: 
// interface Person {
//   id: string;
//   age: number;
// }

Pick

与Omit之相反的是Pick,它允许您创建一个新类型,该新类型仅包含现有类型的一部分属性

interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

type UserWithEmailAndName = Pick<User, 'email' | 'name'>;

// same as: 
// interface Person {
//   name: string;
//   email: string;
// }

多种类型一起使用

interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

type PartialPick = Partial<Pick<User, 'email' | 'name'>>;

// same as: 
// interface Person {
//   name?: string | undefined;
//   email?: string | undefined;
// }

另一个例子:

interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

type OmitPartialPick = Omit<Partial<Pick<User, 'email' | 'name'>>, 'email'>;

// same as: 
// interface Person {
//   name?: string | undefined;
// }

Readonly

Readonly类型允许您从现有类型中创建新类型,并且在初始化后无法修改任何属性。

interface Person {
  id: number;
  name: string;
  age: number;
}

type ReadonlyPerson = Readonly<Person>;

// same as:
// interface Person {
//   readonly id: number;
//   readonly name: string;
//   readonly age: number;
// }

const person: ReadonlyPerson = {
  id: 1,
  name: 'John',
  age: 25
};

person.name = 'Mike'; // Error: Cannot assign to 'name' because it is a read-only property.

Mutable

Mutable允许您将所有只读类型转换为可变类型。

interface Person {
  readonly id: number;
  readonly name: string;
  readonly age: number;
}

// The syntax for Mutable is as follows:
type Mutable<T> = {
  -readonly [P in keyof T]: T[P];
};

type MutablePerson = Mutable<Person>;

// same as:
// interface Person {
//   id: number;
//   name: string;
//   age: number;
// }

const person: MutablePerson = {
  id: 1,
  name: 'John',
  age: 25
};

person.name = 'Mike'; // Okay
person.id = 2; // Okay

Exclude

Exclude类型允许您通过删除一个成员来创建一个新类型

type NumberOrString = number | string;
type OnlyNumber = Exclude<NumberOrString, string>;

// same as:
// type OnlyNumber = number;

const num: OnlyNumber = 5;
const str: OnlyNumber = 'hello'; // Error: Type '"hello"' is not assignable to type 'number'.

甚至可以exlude多个联合成员:

type NumberStringOrBoolean = number | string | boolean;
type OnlyBoolean = Exclude<NumberStringOrBoolean, string | number>;

// same as:
// type OnlyBoolean = boolean;

Extract

与Exclude相反的是Extract类型,它允许您从并集中拾取一个或多个成员:

type NumberOrString = number | string | boolean;
type OnlyNumber = Extract<NumberOrString, number>;

// same as:
// type OnlyNumber = number;

ReturnType
ReturnType实用程序类型允许您提取函数类型的返回类型。它将函数类型作为参数,并返回函数返回的值类型。

function add(a: number, b: number): number {
  return a + b;
}

type AddReturnType = ReturnType<typeof add>;
// type AddReturnType = number;

// ---

function addStr(a: string, b: string): string{
  return a + b;
}

type AddReturnType2 = ReturnType<typeof addStr>;
// type AddReturnType2 = string;

Parameters
Parameters类型用于从函数中提取参数类型。

function add(a: number, b: string, c:boolean): string {
  return a + b;
}

type AddReturnType = Parameters<typeof add>;
// type AddReturnType = [a: number, b: string, c:boolean];

NonNullable

NonNullable类型允许您通过从给定类型中排除null和undefined来创建新类型。

type NullableString = string | null | undefined;

type NonNullableString = NonNullable<NullableString>;
// type NonNullableString = string;

const str1: NullableString = null;
const str2: NonNullableString = 'hello';
const str3: NonNullableString = null; // Error: Type 'null' is not assignable to type 'string'.

Awaited
Awaited类型允许您提取promise或其他使用await的类型的解析类型。

type promiseNumber = Promise<number>

type justNumber = Awaited<Promise<number>>
// type justNumber = number

Awaited和ReturnType组合使用

async function fetchData(): Promise<string> {
  // fetch data from API and return a string
}

type ResolvedResult = Awaited<ReturnType<typeof fetchData>>;
// type ResolvedResult = string

在这个例子中,我们定义了一个async异步函数,它返回一个字符串的Promise(Promise<string>)。然后,我们使用ReturnType提取fetchData的返回类型,并将其作为参数传递给Awaited,以获取promise的最后的解析类型。

上一篇: go get github.com/gin-gonic/gin 下载失败解决方法  下一篇: Element.scrollTo之IE兼容  

必须知道的Typescript实用类型相关文章