I want to create a function that takes two parameters, a key and a value, but I can't do it with typescript. Perhaps this is a duplicate question, then direct me to the original question, on my own I could not find the answer
interface SomeObject {
key1: string;
key2: number;
key3: boolean;
}
class SomeClass {
public fields: {
[field in keyof SomeObject]: SomeObject[field];
};
constructor() {
this.fields = {
key1: "",
key2: 123,
key3: false,
};
}
setValue = (
key: keyof SomeObject,
value: SomeObject[keyof SomeObject],
): void => {
this.fields[key] = value;
};
}
CodePudding user response:
There's currently nothing tying your key
and value
arguments together. I assume, for example, that if 'key1'
is passed as the key, then the type of value
should be string
?
You can achieve this linked type functionality using generics:
setValue<T extends keyof SomeObject>(
key: T,
value: SomeObject[T],
): void {
this.fields[key] = value;
}