I've recently delved into TypeScript coding and have run into a puzzling issue that has me stumped.
Take a look at the code snippet 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");
}
To give you some context on what I'm aiming for: the selectorFunction
is designed to fetch a value from testObject
, based on the key it receives, while ensuring the correct data type. This is why the key property's type is set as generic.
Everything seems to work fine by itself, but things get complicated when optional properties are introduced, causing a conflict with the method's required return type to prevent undefined values.
In theory, it should be straightforward—just add an 'if' check to verify the property's existence, right? Despite attempting this fix, TypeScript continues to flag 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)