i have recently started writing in TypeScript, and i have encountered a problem that i can't seem to find an answer for.
Consider the code below:
interface testInterface {
a: string;
b: number;
c?: number;
}
const testObject: testInterface = {
a: "1",
b: 2,
};
function selectorFunction<GenericKey extends keyof testInterface>(
key: GenericKey
): Required<testInterface>[keyof testInterface] {
if (testObject[key]) return testObject[key];
throw new Error("Error");
}
A bit of explanation what i'm trying to achieve: the selectorFunction
is supposed to return a value from the testObject
, based on a key that it receives, while also having the correct type for that value. That's why the key property type is Generic.
On it's own it works fine, the problem starts when optional properties come into play, as the method return type is required, so that the method does not return any undefined values.
In theory it should be easy, just add an if to check if that property exists, and it should work, but typescript still gives me the following error:
Type 'string | number | undefined' is not assignable to type 'string | number'.
Type 'undefined' is not assignable to type 'string | number'.
Type 'testInterface[GenericKey]' is not assignable to type 'number'.
Type 'string | number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.ts(2322)