gpt4 book ai didi

javascript - 创建一个接口(interface),其键是枚举的值

转载 作者:行者123 更新时间:2023-12-02 22:46:54 25 4
gpt4 key购买 nike

假设我有一个枚举

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com