My goal is to update an object with a specific interface programmatically. I have defined the interface as follows:
interface ITypes {
num: number;
str: string;
bol: boolean;
};
const obj: Partial<ITypes> = {}; // This is the object I want to update programmatically
I am looking for a way to specify a key
and a val
in order to update my obj
. The key should be limited to one of the keys from the ITypes
interface, and the value should match the type specified at the selected key from the interface. Initially, I achieved this by using the following code:
const key: keyof ITypes = "num"; // The key must be from the ITypes interface
const val: ITypes[typeof key] = 1; // The val must match the type specified at 'num' - 'number'
obj[key] = val;
Although the above method works, I now aim to define both the key
and val
within an object, which requires me to create an interface. However, I encountered challenges with defining the type for val
. Here's what I've attempted so far:
interface IUpdatePayload {
key: keyof ITypes;
val: ITypes[typeof this.key]; // The error 'Type 'any' cannot be used as an index type.' occurs here
};
const updatePayload: IUpdatePayload = {key: "num", val: "1"}; // It should flag an error that 'val' is not a number
obj[updatePayload.key] = updatePayload.val;
I tried referencing the interface's key
type using typeof this.key
, as suggested in this answer, but it resulted in the error
Type 'any' cannot be used as an index type.
. Perhaps this occurred because the key was not yet defined with a value like in the initial working example using variables. My question is, is there a solution to enable val
to adopt the type determined by key
as outlined in the ITypes
interface?