Typescript从接口获取键值


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接口创建键值查找?也许是通过反思?

更新

我使用与C#名称类似的解决方案解决了这个问题。

export function nameOf<T>(name: Extract<keyof T, string>): string {
return name;
}
nameOf<Cookies>('Authentication') // = 'Authentication'

确定:

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>

最新更新