6 种最实用的TypeScript类型

89 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第30天,点击查看活动详情 原文链接:fuelerhq

我已经使用TypeScript快一年了,在这段时间我学会了很多东西并用到了很多TypeScript类型!本文主要分享6种实用的TypeScript类型。

Record

如果你想构造一个对象类型,属性是type,值也是type类型。例如你想创建一个对象类型来存储用户的数据,你可以使用Record来实现!

// Our user ID will be a string
type UserID = string

// Defining our available user information types
type UserInfo = {
  name: string;
  email: string;
  avatarUrl: string;
}

const users: Record<UserID, UserInfo> = {
 "uuid1": { "name": "user1", "email": "user1@gmail.com", "avatarUrl": "https://user1.com/avatar.png" },
 "uuid2": { "name": "user2", "email": "user2@gmail.com", "avatarUrl": "https://user2.com/avatar.png" },
 "uuid3": { "name": "user3", "email": "user3@gmail.com", "avatarUrl": "https://user3.com/avatar.png" }
 }

Partial

当你想要使用现有类型但希望所有属性都是可选的时,你可以使用Partial。 假设你想要更新用户的一个属性,并且你已经拥有一个包含所有必需属性的用户interface,但你不想创建单独的interface来更新用户信息。使用 Partial 实用程序,你可以动态创建具有所有属性的类型作为可选。

// User interface with all required properties
interface User{
 id:string;
 name: string;
 slug: string;
 group: string[];
 avatarUrl: string;
 about: string;
}

// Partial<User> generates a new type based on User with all the property
// keys being optional
const updateUser: Partial<User> = {
  about: 'I am a software engineer.'
}

Required

Required 实用程序类型与 Partial 实用程序类型完全相反,当你想要使用现有类型但希望所有属性都是必需的时,它非常有用。

// User type has lastName property as optional
type User = {
    firstName: string,
    lastName?: string
}

// You want to create a user with both firstName and lastName, so you can use User type with Required utility type to make all the properties as required.
const user1: Required<User> = {
    firstName: "John",
    lastName: "Doe"
}

Omit

用于通过省略另一个对象类型的特定属性来创建对象类型。假设你有一个具有一些属性 X、Y 和 Z 的对象类型用户。如果你想创建一个没有属性 Z 的对象类型,那么您可以使用此实用程序类型。

type Product = {
  X: string;
  Y: string;
  Z: string;
}

type ProductWithoutZ = Omit<Product, "Z">;

Pick

可以从现有类型中选择属性来创建新类型。当你有一个子组件与父组件有一些共同的属性时,您可以通过选择这些属性来为子组件创建一个类型。

type ParentType = {
  X: string;
  T: number;
  S: boolean;
}

type ChildType = Pick<ParentType, "X" | "S">


Exclude

使用联合类型时,当你仅对某些成员而不是全部成员使用联合类型,可以使用 Exclude 实用程序来实现相同的目的。

type ReactionUnion = '👍' | '👎' | '😄' |  '🎉' | '😕' | '❤️' | '👀' | '🚀'

// This is equivivalent to  '👍' | '👎' 
type OnlyThumbsUnion = Exclude<ReactionUnion , '😄' |  '🎉' | '😕' | '❤️' | '👀' | '🚀'>

概括

在本文中,我们讨论了 6 种 TypeScript 实用程序类型,它们将帮助我们编写更好的 typescript 代码。TypeScript 提供了更多的实用程序类型,你可以在 这里查看它们。