[英]Typescript type: Object with static/fixed keys and dynamic keys
How do I create a typescript type for an object, where I can have a fixed set and dynamic set of keys?如何为对象创建打字稿类型,在那里我可以拥有一组固定的键和动态的键集? For example:
例如:
export type APIOMethods = 'getA' | 'getB' | 'getC';
export type item = {
divId: string;
role: string;
[key: K in APIMethods]?: any;
};
// Not working ↑↑↑ 🔴
export type item = {
divId: string;
role: string;
[key: APIMethods]: any;
};
// Not working ↑↑↑ 🔴
// the object could look like this:
{divId: '', role: '', getA: {}} OR
{divId: '', role: '', getB: {}} OR
{divId: '', role: '', getC: {}}
Solution: using a mapped object type :解决方案:使用映射对象类型:
export type item = {
[key in APIMethods]?: any;
} & {
divId: string;
role: string;
};
After fiddling around with the code more inside of Visual Studio Code , the editor ended up making a suggestion to use a mapped object type when I had type this earlier在Visual Studio Code内部更多地摆弄代码之后,编辑器最终建议使用映射对象类型,因为我之前输入了它
export type item = {
divId: string;
role: string;
[key: APIMethods]: any;
^🔴 An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.ts(1337)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.