Search code examples
typescripttsc

How to cast keyof exports to string type


I have this:

export const USER_SETTINGS_UPDATED = 'c_USER_SETTINGS_UPDATED';
export const GET_USER = 'c_GET_USER';
export const EMAIL_RECORDS_RECEIVED = 'c_EMAIL_RECORDS_RECEIVED';

export type UserConstants = keyof typeof exports;

the problem is that UserConstants is not a string, but instead string | number | symbol...is there a way to cast UserConstants to a string type, or better yet, get the values instead of the keys?

GOAL: I am looking for a type that looks like:

type UserConstants = 'c_USER_SETTINGS_UPDATED' | 'c_GET_USER' | 'c_EMAIL_RECORDS_RECEIVED'

I tried this:

type ValueOf<T> = T[keyof T];
export type UserConstants = ValueOf<typeof exports>;

but that simply yields:

type UserConstants = string

Solution

  • You can do this by dynamically importing the source file with import().

    For example: Playground

    export const USER_SETTINGS_UPDATED = 'c_USER_SETTINGS_UPDATED';
    export const GET_USER = 'c_GET_USER';
    export const EMAIL_RECORDS_RECEIVED = 'c_EMAIL_RECORDS_RECEIVED';
    
    export type UserConstants = typeof import('./input')[keyof typeof import('./input')];
    

    You do not need an extra object as Chris implies.