TypeScript — ประกาศ Twin Types ด้วย Utility Omit

wk
1 min readJun 14, 2020

--

ตัวอย่างนี้ อ้างอิงจาก Twin types — properties synchronization without inheritance ที่เจ้าของบทความสร้าง Twin types ผ่าน Roslyn analyser (C# ไม่สามารถประกาศ Twin types ได้โดยตรง)

ตัวอย่าง

จากตัวอย่างมี type User และ Address โดย User unoin กับBase ส่วน Address ไม่มีความสัมพันธ์กับ type อื่น

ความต้องการ คือ ต้องการ UserDetails (Twin type) ที่คล้ายกับการเอา User และ Address มารวมกัน แต่ไม่เอาฟิลด์ login ของ User และ no ของ Address

ใน TypeScript สามารถประกาศ type ใหม่จากความต้องการนี้ด้วย Utility class ชื่อ Omit ตาม syntax ต่อไปนี้

type UserDetails = Omit<User & Address, "login" | "no">

ความหมาย คือ ให้เอาฟิลด์ของ User และ Address มารวมกันแลัวตัด login และ no ออก โดย type ใหม่ที่ได้ สามารถนำไปใช้ ดังนี้

function process(userDetails: UserDetails) { }process({ 
id: 1,
version: 1,
tenantId: 1,
firstName: "wk",
lastName: "wk",
city: "Bangkok"
})

--

--

No responses yet