Dark mode
Indexed Access Types
ใช้สำหรับเข้าถึงประเภทของ property ใน object type
Basic Usage
Object Properties
ใช้สำหรับเข้าถึง type ของ property โดยตรงจาก object type
ts
type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"]; // number
Union Types
สามารถใช้ union type เป็น index เพื่อเข้าถึง type ของหลาย property พร้อมกัน
ts
type Person = { age: number; name: string; alive: boolean };
type I1 = Person["age" | "name"]; // string | number
Advanced Usage
Arrays and Tuples
ใช้ typeof ร่วมกับ indexed access เพื่อดึง type ของ array elements
ts
const MyArray = [
{ name: "Alice", age: 15 },
{ name: "Bob", age: 23 },
];
type Person = typeof MyArray[number]; // { name: string; age: number }
Const Index Signatures
ใช้กับ object ที่มี index signature เพื่อเข้าถึง type ของ property ที่ไม่รู้ชื่อล่วงหน้า
ts
type Mapish = { [k: string]: boolean };
type M = Mapish["foo"]; // boolean