I have a TypeScript interface:
interface MyInterface {
key1: string;
key2: number;
key3: SomeOtherType;
}
Then I have a class, which has (among other things) a private property that conforms to that interface:
class MyHandler {
constructor(private myObject: MyInterface, ...otherThings) {}
}
I want to add an updateMyObject
method to the class, which takes keyof MyInterface
as the first argument and the value to update as the second argument.
class MyHandler {
...
updateMyObject(key: keyof MyInterface, value: ???) {
this.myObject[key] = value
}
}
The interface has about 6 keys with some user-defined (or developer defined to be precise) types. I want to make sure that the user passes the correct type of argument when they call the update method. How can I ensure that? Is there a way to make sure, if a user passes key1
as the first argument, the second argument is of type string
, for key3 it's SomeOtherType
, and so on?
An obvious thing: If I go for implicit any
type assignment, it shows me the error: Type 'any' is not assignable to type 'never'.
I have referred to this question, but what the answer suggests gives me the following error:
Type 'string | number | ...' is not assignable to type 'never'.
It also makes me wonder, why is the type of this.myObject[key]
never
when I have assigned it a correct type at the time of declaration?