我正在尝试创建带有联合类型键的松散类型对象的接口。
export type ObjectsType = 'text' | 'image' | 'circleText';
export interface IAllowedObjects {
[key: ObjectsType] : boolean;
}
但得到
索引签名参数类型不能为联合类型。考虑 而是使用映射的对象类型
已经尝试了一些解决方案,但是没有运气。
export type ObjectsType = 'text' | 'image' | 'circleText';
export interface IAllowedObjects {
[key in ObjectsType] : boolean;
}
接口中的计算属性名称必须引用表达式 其类型为文字类型或“唯一符号”
计算出的属性名称必须为'string','number','symbol', 或“任何”。
答案 0 :(得分:1)
您只能用mapped type来定义type aliases,接口不能这样做。
export type ObjectsType = 'text' | 'image' | 'circleText';
export type IAllowedObjects = {
[key in ObjectsType]: boolean;
}
答案 1 :(得分:1)
您还可以使用Record实用程序类型,它与福特回答的用途相同
type ObjectsType = 'text' | 'image' | 'circleText'
type IAllowedObjects = Record<ObjectsType, boolean>