作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有一个枚举
export enum status {
PENDING = 'pending',
SUCCESS = 'success',
FAIL = 'fail'
}
假设这个枚举在多个地方使用(即,我不能只是用其他东西替换它)。不过,我确实希望其他开发者将来能够添加/删除状态。
现在,我有一个对象 obj,我希望它看起来像如下
let obj = {
pending: 10,
success: 20,
fail: 0
}
我想为该对象定义一个接口(interface)。我可以做类似的事情
interface objInterface = {
[key: string]: number;
}
但是,现在有人可以将 obj 设置为
obj = {
flip: 3333
}
我不希望这种情况发生,我只想要挂起、成功、失败,如上面枚举中所定义。
理想情况下,我会做类似的事情
interface objInterface = {
[key: TransactionStatus] : number;
}
但这不起作用 - 它给出了这个错误:
(parameter) key: TransactionStatus An index signature parameter type cannot be a union type. Consider using a mapped object type instead.ts(1337)
最好的方法是什么?
我试过了
type objType = {
[K in keyof typeof status]: number;
};
但是当我将鼠标悬停在它上面时,我看到它转换为
type objType = {
readOnly PENDING: number,
readOnly SUCCESS: number,
readOnly FAIL: number
}
最佳答案
知道了
type objType = {
[K in status]: number;
};
关于javascript - 创建一个接口(interface),其键是枚举的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58359639/
我是一名优秀的程序员,十分优秀!