Reputation: 705
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',
};
I want to enforce the COOKIE_KEYS, so that each key is equal to value.
Authentication = 'Authentication'
Is there a way to create a key-value lookup from keyof interface? Perhaps via reflection?
I solved this problem by using similar solution to C# nameOf.
export function nameOf<T>(name: Extract<keyof T, string>): string {
return name;
}
nameOf<Cookies>('Authentication') // = 'Authentication'
Upvotes: 3
Views: 933
Reputation: 33051
Sure:
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>
Upvotes: 2