I have an object with the following interface that I would like to update programatically:
interface ITypes {
num: number;
str: string;
bol: boolean;
};
const obj: Partial<ITypes> = {}; // I want to update this programatically
I want to be able to define a key and a val and update my obj using those values. I want it so that the key can only be one of the keys from the ITypes interface, and the value would then be need to be the type specified at the selected key from the interface. I can do this just fine using the below code:
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;
The above code works fine, however, now, instead of having key and val as seperate variables, I want to define them in an object, and so I need to define an interface. However, I'm having trouble with the type definition for val. This is what I have tried so far:
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;
I've tried to self-reference the interface's key type using typeof this.key (which I saw suggested in this answer) however that is erroring with Type 'any' cannot be used as an index type., I'm guessing it's because key hasn't actually been defined to have a value like in the first working example using variables. My question is, is there a way to make this work so that val takes on the type defined by key as specified in the ITypes interface?