เจนเนอริก - Typescript ดึงค่ากุญแจจาก Interface
export interface Cookies {
Authentication: string;
Refresh: string;
DeviceId: string;
}
type key = keyof Cookies
// key is "Authentication" | "Refresh" | "DeviceId"
export const COOKIE_KEYS: Record<key, key> = {
Authentication: 'Authentication',
Refresh: 'Refresh',
DeviceId: 'DeviceId',
};
ฉันต้องการบังคับใช้ COOKIE_KEYS เพื่อให้แต่ละคีย์เท่ากับค่า
การตรวจสอบตัวตน='การตรวจสอบตัวตน'
มีวิธีในการสร้างการค้นหาค่าคีย์-ค่า จาก keyof interface ไหม? อาจจะผ่านการสะท้อนข้อมูล?
อัปเดต
ฉันแก้ปัญหานี้โดยใช้วิธีการที่คล้ายกับ nameOf ของ C#
export function nameOf<T>(name: Extract<keyof T, string>): string {
return name;
}
nameOf<Cookies>('Authentication') // = 'Authentication'
คำตอบ #1
แน่นอน :
export interface Cookies {
Authentication: string;
Refresh: string;
DeviceId: string;
}
type Keys = keyof Cookies
/**
* Iterate through every key of Cookies
* and assign key to value
*/
type Make<T extends string>={
[P in T]:P
}
type Result = Make<Keys>
