英文:
How to add dynamic keys to type for reference in Typescript?
问题
我有一个情景,其中键来自后端,我需要根据这些键创建一个接口。因此,动态接口将帮助我绑定这些属性。
const KEYS_FROM_API = ['ARE_YOU_SURE', 'NOT_NOW', 'GO_BACK'];
// 使用 KEYS_FROM_API 数组动态创建类型
type DYNAMIC_KEYS_TYPE = typeof KEYS_FROM_API[number];
// 使用 Record 创建动态接口
type ResultType = Record<DYNAMIC_KEYS_TYPE, string>;
// RESULT 包含了动态接口的键值对
const RESULT: ResultType = { ARE_YOU_SURE: '你确定吗', NOT_NOW: '现在不', GO_BACK: '返回' }
// 这将正常工作
console.log(RESULT.ARE_YOU_SURE, RESULT.NOT_NOW, RESULT.GO_BACK);
在上面的代码中,我使用了 typeof KEYS_FROM_API[number]
来动态创建 DYNAMIC_KEYS_TYPE
类型,使其根据 KEYS_FROM_API
数组的内容进行动态定义。然后,使用 Record
创建了动态接口 ResultType
。这样,您就可以根据从后端获取的键动态创建类型。
英文:
I have a scenario where the keys come from backend and I need to create an interface as per the keys. So the dynamic interface will help me bind those properties.
const KEYS_FROM_API = ['ARE_YOU_SURE', 'NOT_NOW', 'GO_BACK'];
// added type statically.
type DYNAMIC_KEYS_TYPE = 'ARE_YOU_SURE' | 'NOT_NOW' | 'GO_BACK'
// created dynamic interface using Record
type ResultType = Record<DYNAMIC_KEYS_TYPE, string>
// RESULT holds key value pair of type object and type of dynamic interface i.e ResultType
const RESULT: ResultType = { ARE_YOU_SURE: 'Are You sure', NOT_NOW: 'Not Now', GO_BACK: 'go back'}
// this works fine
console.log(RESULT.ARE_YOU_SURE, RESULT.NOT_NOW, RESULT.GO_BACK);
Here the above code works as per my expectation and also there is no linting error as the RESULT constant has a type where it gets all the properties from the interface.
Now I want to create DYNAMIC_KEYS_TYPE dynamically using the KEYS_FROM_API array. The type must be created dynamically using the Array. In the above example I have created hard coded.
Help me out creating DYNAMIC_KEYS_TYPE from KEYS_FROM_API array.
答案1
得分: 1
You need to add as const
to KEYS_FROM_API
to make it more strict than just string[]
, then you can use typeof KEYS_FROM_API[number];
const KEYS_FROM_API = ['ARE_YOU_SURE', 'NOT_NOW', 'GO_BACK'] as const;
// expected: type DYNAMIC_KEYS_TYPE = 'ARE_YOU_SURE' | 'NOT_NOW' | 'GO_BACK'
type DYNAMIC_KEYS_TYPE = typeof KEYS_FROM_API[number];
// ^? type DYNAMIC_KEYS_TYPE = 'ARE_YOU_SURE' | 'NOT_NOW' | 'GO_BACK'
英文:
You need to add as const
to KEYS_FROM_API
to make it more strict that just string[]
, then you can use typeof KEYS_FROM_API[number];
const KEYS_FROM_API = ['ARE_YOU_SURE', 'NOT_NOW', 'GO_BACK'] as const;
// expected: type DYNAMIC_KEYS_TYPE = 'ARE_YOU_SURE' | 'NOT_NOW' | 'GO_BACK'
type DYNAMIC_KEYS_TYPE = typeof KEYS_FROM_API[number];
// ^? type DYNAMIC_KEYS_TYPE = 'ARE_YOU_SURE' | 'NOT_NOW' | 'GO_BACK'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论