I am looking to create a type-safe getter function that has the ability to return modified values while still being sound.
class Foo {
a: number;
b: boolean;
}
function getProp<K extends keyof Foo>(o: Foo, p: K): Foo[K] {
switch (p) {
case 'a':
return 1;
case 'b':
return o[p];
}
return undefined;
}
In the provided code snippet, I intended for getProp
to return Foo[K]
in this scenario:
const v = getProp(f, 'a')
where v
is of type number
. However, an error is thrown when attempting to return 1
because it cannot be assigned to never
.
It should be noted that this behavior worked in Typescript 3.4 thanks to "Fixes to unsound writes to indexed access types" ().
What would be the best approach to address this issue without resorting to using return 1 as any
?