【问题标题】:Loosely typed object with union type key in typescript打字稿中具有联合类型键的松散类型对象
【发布时间】:2020-04-19 05:03:45
【问题描述】:

我正在尝试使用联合类型键创建松散类型对象的接口。

export type ObjectsType = 'text' | 'image' | 'circleText';

export interface IAllowedObjects {
    [key: ObjectsType] : boolean;
}

但得到

索引签名参数类型不能是联合类型。考虑 改为使用映射对象类型

已经尝试了一些解决方案,但没有成功。

  1. 试过This解决方案
    export type ObjectsType = 'text' | 'image' | 'circleText';
    export interface IAllowedObjects {
         [key in ObjectsType] : boolean;
    }

接口中的计算属性名称必须引用表达式 其类型是文字类型或“唯一符号”

计算属性名称的类型必须为“字符串”、“数字”、“符号”、 或“任何”。

【问题讨论】:

    标签: typescript interface typescript-typings


    【解决方案1】:

    你只能用type aliases定义一个mapped type,接口不能这样做。

    export type ObjectsType = 'text' | 'image' | 'circleText';
    export type IAllowedObjects =  {
      [key in ObjectsType]: boolean;
    }
    

    Code sample

    【讨论】:

    • 谢谢,解决方案有效,我导出的是界面而不是类型。
    【解决方案2】:

    您也可以使用Record 实用程序类型,其作用与 fords answer 相同

    type ObjectsType = 'text' | 'image' | 'circleText'
    type IAllowedObjects = Record<ObjectsType, boolean>
    

    【讨论】:

      猜你喜欢
      • 2021-02-05
      • 2022-01-05
      • 1970-01-01
      • 2020-03-03
      • 2018-06-08
      • 2018-12-06
      • 2021-09-22
      • 2017-05-18
      • 1970-01-01
      相关资源
      最近更新 更多