【发布时间】:2021-08-21 06:45:03
【问题描述】:
我想以编程方式更新具有以下接口的对象:
interface ITypes {
num: number;
str: string;
bol: boolean;
};
const obj: Partial<ITypes> = {}; // I want to update this programatically
我希望能够定义 key 和 val 并使用这些值更新我的 obj。我想要它,以便key 只能是来自ITypes 接口的键之一,然后该值需要是从接口中选择的key 指定的类型。我可以使用以下代码很好地做到这一点:
const key: keyof ITypes = "num"; // key must be a key from the ITypes interface
const val: ITypes[typeof key] = 1; // val must be the type specified at `"num"` - `number`
obj[key] = val;
上面的代码工作正常,但是,现在,我不想将key 和val 作为单独的变量,而是想在一个对象中定义它们,所以我需要定义一个接口。但是,val 的类型定义有问题。这是我迄今为止尝试过的:
interface IUpdatePayload {
key: keyof ITypes;
val: ITypes[typeof this.key]; // Type 'any' cannot be used as an index type.
};
const updatePayload: IUpdatePayload = {key: "num", val: "1"}; // should complain that `val` is not a number
obj[updatePayload.key] = updatePayload.val;
我尝试使用typeof this.key(我在this answer 中看到建议)自引用接口的key 类型,但是Type 'any' cannot be used as an index type. 出错,我猜这是因为密钥没有实际上被定义为具有像第一个使用变量的工作示例中的值。我的问题是,有没有办法让这个工作,让val 采用key 定义的类型,如ITypes 接口中指定的那样?
【问题讨论】:
标签: typescript interface