Skip to content

Mapped Types

ช่วยให้เราสามารถสร้างประเภทใหม่โดยการแปลง property ของประเภทที่มีอยู่

Basic Syntax

Simple Mapped Type

สร้าง type ใหม่โดยการ map ผ่าน properties ของ type เดิม

ts
type 
OptionsFlags
<
T
> = {
[
Property
in keyof
T
]: boolean;
}; type
FeatureFlags
= {
darkMode
: () => void;
newUserProfile
: () => void;
}; type
FeatureOptions
=
OptionsFlags
<
FeatureFlags
>;
// { darkMode: boolean; newUserProfile: boolean }

Modifiers

สามารถเพิ่มหรือลบ modifier อย่าง readonly และ optional ได้

ts
// เพิ่ม readonly ให้ทุก property
type 
Readonly
<
T
> = {
readonly [
P
in keyof
T
]:
T
[
P
];
}; // ทำให้ทุก property เป็น optional type
Partial
<
T
> = {
[
P
in keyof
T
]?:
T
[
P
];
};

Advanced Usage

Key Remapping

ใช้ as clause ในการเปลี่ยนชื่อ key ขณะทำ mapping

ts
type 
Getters
<
T
> = {
[
P
in keyof
T
as `get${
Capitalize
<string &
P
>}`]: () =>
T
[
P
];
};

Built-in Mapped Types

TypeScript มี mapped types ที่ใช้งานบ่อยมาให้แล้วเช่น Readonly, Partial, Required

ts
interface FeatureFlags {
  
darkMode
: () => void;
newUserProfile
: () => void;
} // ตัวอย่างการใช้ Required<T> type
Required
<
T
> = {
[
P
in keyof
T
]-?:
T
[
P
];
}; // ตัวอย่างการใช้ Readonly<T> type
ReadonlyFeatureFlags
=
Readonly
<FeatureFlags>;
// { readonly darkMode: () => void; readonly newUserProfile: () => void; } // ตัวอย่างการใช้ Partial<T> type
PartialFeatureFlags
=
Partial
<FeatureFlags>;
// { darkMode?: () => void; newUserProfile?: () => void; }