跳至主要内容

[TS] TypeScript Utility Types

此篇為各筆記之整理,非原創內容,資料來源可見下方連結與文後參考資料:

產生的型別是 primitive type

keywords: Extract, Exclude
  • Extract:只要取出,從許多項目中挑出能夠符合(extends)特定規則的
  • Exclude:排除後留下,從許多項目中排除符合(extends)特定規則的
/**
* Extract<Type, Union>:從原本的 Type 中取出符合規則的(Exclude 的相反)
**/
type Extract<T, U> = T extends U ? T : never; // 實作

type OnlyString = Extract<'a' | 'b' | 1 | 2, string>; // "a" | "b"

/**
* Exclude<Type, ExcludeUnion>:從原本的 Type 中移除符合規則的
*/
type Exclude<T, U> = T extends U ? never : T; // 實作

enum PlaceType {
PARK = 'park',
ZOO = 'zoo',
OFFICE = 'office',
}
type WillGo = Exclude<PlaceType, PlaceType.OFFICE>; // type WillGo = Place.PARK | Place.ZOO
提示

never 是空集合(empty set)的概念,以 Extract 來說,如果符合就留下,否者就剔除(never);相反的,以 Exclude 來說就是符合就剔除(never),否則就留下。

產生新的物件型別

keywords: Partial, Required, Pick, Omit, Record,

下面的 utility 都會根據一個「物件型別」產生新的「物件型別」

  • Partial - Required
  • Pick - Omit
/**
* Record<Keys, Type>:由特定的 key 和相同型別的值,產生的物件型別
*/
interface PlaceInfo {
address: string;
phone: string;
}
type PlaceRecord = Record<PlaceType, PlaceInfo>;
let placeRecord: PlaceRecord = {
[PlaceType.PARK]: {
address: 'foo',
phone: 'bar',
},
[PlaceType.ZOO]: {
address: 'foo',
phone: 'bar',
},
[PlaceType.OFFICE]: {
address: 'foo',
phone: 'bar',
},
};

/**
* Pick<Type, Keys>:從物件中挑出特定屬性及其型別,變成新的物件型別
**/
type Todo = {
title: string;
description: string;
completed: boolean;
};

type TodoPreview = Pick<Todo, 'title' | 'completed'>;
// type TodoPreview = {
// title: string;
// completed: boolean;
// }

/**
* Omit<Type, Keys>:從物件中排除特定屬性及其型別,變成新的物件型別
**/
type Todo = {
title: string;
description: string;
completed: boolean;
};

type TodoPreview = Omit<Todo, 'title' | 'completed'>;
// type TodoPreview = {
// description: string;
// }

/**
* Partial<Type>:把物件的所有屬性都變成 optional 的
**/
type Todo = {
title: string;
description: string;
};

type PartialTodo = Partial<Todo>;

type Todo = {
title: string;
description: string;
};

type PartialTodo = Partial<Todo>;
// type PartialTodo = {
// title?: string | undefined;
// description?: string | undefined;
// }