TypeScript - 使用筆記 (5)

簡介

  • TypeScript 內建的輔助工具類型
  • Utility Types可根據需求,方便的轉換現有的型別,或產生一個新型別
  • 增加程式碼的靈活性和重用性,更精確的定義型別

Partial<Type>

  • Type的所有屬性設定成可選

範例 1

interface User {  id: number  name: string}type PartialUser = Partial<User>// 等同於// {//   id?: number;//   name?: string;// }

範例 2

  • 修改產品價格
interface Product {  title: string  price: number}function updateProduct(product: Product, fieldsToUpdate: Partial<Product>) {  return { ...product, ...fieldsToUpdate }}const product1 = {  title: 'Iphone66',  price: 66}const product2 = updateProduct(product1, {  price: 77})console.log(product2) //{ title: "Iphone66", price: 77}

Required<Type>

  • Type的所有屬性設為必要

範例

interface Props {  a?: number  b?: string}type RequiredProps = Required<Props>// 等同於// {//   a: number;//   b: string;// }const obj: Props = { a:3 }const obj2: :Required<Props> = { a:6 } ❌// Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.

Readonly<Type>

  • Type的所有屬性設定成唯讀

範例

interface Job {  salary: number}const myJob: Readonly<Job> = { salary: 50 }myJob.salray = 99999// Cannot assign to 'salary' because it is a read-only property.

Record<Keys, Type>

  • 建立一個物件型別,屬性鍵來自 Keys,屬性值型別為 Type

範例

  • 屬性值設定為 Role,值只能是 Permission 所定義的內容
type Role = 'Manager' | 'Engineer' | 'HR'type Permission = 'read-only' | 'read-write' | 'no-access'type RolePermissions = Record<Role, Permission>const rolePermissions: RolePermissions = {  Manager: 'read-write',  Engineer: 'read-write',  HR: 'read-only'}rolePermissions.HR = 'fired'// Type '"fired"' is not assignable to type 'Permission'.

Pick<Type, Keys>

  • Type中選取一組屬性Keys來建立新型別

範例

  • Todo中,選取特定的屬性,來建立新型別:TodoPreview
interface Todo {  title: string  description: string  completed: boolean}type TodoPreview = Pick<Todo, 'title' | 'completed'>const todo: TodoPreview = {  title: 'Take a walk',  completed: false}

Omit<Type, Keys>

  • 從 Type 中移除一組屬性 Keys 來建立新型別

範例

interface Todo {  title: string  description: string  completed: boolean}type TodoPreview = Omit<Todo, 'description'>const todo: TodoPreview = {  title: 'Take a walk',  completed: false}

Exclude<Type, ExcludedUnion>

  • Type(通常是Union型別)中移除符合條件的型別

範例

  • 從 Primitive 中移除string型別,value 的值只能是numberboolean
type Primitive = string | number | booleanconst value: Exclude<Primitive, string> = true

Extract<Type, Union>

  • Type(通常是Union型別)中,選出符合條件的型別

範例

  • 從 Primitive 中指定string型別,value 的值只能是string
type Primitive = string | number | booleanconst value: Extract<Primitive, string> = 'Only String'

參考資料

# TypeScript