【问题标题】:Typescript type: Object with static/fixed keys and dynamic keys [duplicate]打字稿类型:具有静态/固定键和动态键的对象[重复]
【发布时间】:2021-12-24 12:57:41
【问题描述】:

如何为对象创建 typescript 类型,我可以在其中拥有一组固定键和动态键集?例如:

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: {}}
  • Typescript Playground 链接here

【问题讨论】:

    标签: javascript typescript typescript-typings typescript-generics


    【解决方案1】:

    解决方案:使用映射对象类型:

    export type item = {
      [key in APIMethods]?: any;
    } & {
      divId: string;
      role: string;
    };
    
    

    在修改了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)
    
    };
    

    【讨论】:

      猜你喜欢
      • 2020-07-15
      • 2020-01-19
      • 2020-03-09
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      相关资源
      最近更新 更多