3
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?

Update

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'

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you so much. I end it up by simplify this to, type CookieMap = { [P in keyof Cookies]: P; };

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.