如何将 keyof 导出转换为字符串类型
How to cast keyof exports to string type
我有这个:
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;
问题是 UserConstants
不是字符串,而是 string | number | symbol
...有没有办法将 UserConstants
转换为字符串类型,或者更好的是,得到值而不是键?
目标:我正在寻找如下类型:
type UserConstants = 'c_USER_SETTINGS_UPDATED' | 'c_GET_USER' | 'c_EMAIL_RECORDS_RECEIVED'
我试过这个:
type ValueOf<T> = T[keyof T];
export type UserConstants = ValueOf<typeof exports>;
但这只会产生:
type UserConstants = string
typeof exports
是 any
,所以 keyof typeof exports
是 symbol | string | symbol
。
您可以使用常量声明一个对象,将其导出为默认值,并另外导出类型。那应该让你得到你想要的。每个单独的常量都是可导入的,UserConstants
类型也是如此。
const constants = {
USER_SETTINGS_UPDATED: 'c_USER_SETTINGS_UPDATED',
GET_USER: 'c_GET_USER',
EMAIL_RECORDS_RECEIVED: 'c_EMAIL_RECORDS_RECEIVED',
}
export type UserConstants = keyof typeof constants;
export default constants;
您可以通过 import()
.
动态导入源文件来做到这一点
例如: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')];
您不需要克里斯暗示的额外对象。
我有这个:
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;
问题是 UserConstants
不是字符串,而是 string | number | symbol
...有没有办法将 UserConstants
转换为字符串类型,或者更好的是,得到值而不是键?
目标:我正在寻找如下类型:
type UserConstants = 'c_USER_SETTINGS_UPDATED' | 'c_GET_USER' | 'c_EMAIL_RECORDS_RECEIVED'
我试过这个:
type ValueOf<T> = T[keyof T];
export type UserConstants = ValueOf<typeof exports>;
但这只会产生:
type UserConstants = string
typeof exports
是 any
,所以 keyof typeof exports
是 symbol | string | symbol
。
您可以使用常量声明一个对象,将其导出为默认值,并另外导出类型。那应该让你得到你想要的。每个单独的常量都是可导入的,UserConstants
类型也是如此。
const constants = {
USER_SETTINGS_UPDATED: 'c_USER_SETTINGS_UPDATED',
GET_USER: 'c_GET_USER',
EMAIL_RECORDS_RECEIVED: 'c_EMAIL_RECORDS_RECEIVED',
}
export type UserConstants = keyof typeof constants;
export default constants;
您可以通过 import()
.
例如: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')];
您不需要克里斯暗示的额外对象。