【发布时间】:2021-04-13 16:37:04
【问题描述】:
我定义了一个字符串的 OR 类型(由于不相关的情况,这不能是枚举)
export type AnimalTypes =
| 'dog'
| 'cat'
| 'donkey'
| 'elephant';
我使用这个类型作为导出的Record中的值
export const PartyTypes: Record<string, AnimalTypes> = {
DOG_PARTY: 'dog',
CAT_PARTY: 'cat',
DEMOCRAT_PARTY: 'donkey',
REPUBLICAN_PARTY: 'elephant',
};
在一个单独的文件中,我导入上面的两个,并以AnimalType 为键创建一个接口
interface ElectionState {
votesByParty: Record<AnimalTypes, PartyVotesCollection>;
}
当我尝试使用 PartyTypes 记录实现此接口的对象字面量时,对象键出现错误
export const initialState: ElectionState = {
votesByParty: {
PartyTypes.DOG_PARTY: {
electionsWon: 0,
voteCount: 0,
},
},
};
Type '{ PartyTypes: Record
中不存在 'PartyTypes'; ““: 任何; }' 不可分配给类型 'Record '。 对象字面量只能指定已知属性,并且类型 'Record '.ts(2322)
如何使用 Record 的值作为从接口继承的另一个对象的键?
【问题讨论】:
标签: typescript