Struggling with discriminating between private class member types? Attempting to access variables v1
and v2
using string literals resulting in type union issues. With a bit of tweaking, I found a workaround for public members only. Check out this example:
class Test {
private v1: string;
private v2: number;
v3: string;
v4: number;
private v5: string;
private v6: number;
// Works for all members but does not discriminate union
get12(what: 'v1' | 'v2') {
return this[what];
}
// Only works for public members
get34<T extends 'v3' | 'v4'>(what: T) {
return this[what];
}
// Explicit overload method works but is not the lazy/generic solution desired
get56(what: 'v5'): string;
get56(what: 'v6'): number;
get56(what: 'v5' | 'v6') {
return this[what];
}
}
let myTest = new Test();
myTest.get12('v1'); // returns "string | number" type
myTest.get34('v3'); // returns "string" type
myTest.get56('v5'); // returns "string" type
Looking for a workaround that doesn't require explicit overloading or manual maintenance due to variable type changes. Any ideas?
Edit: To clarify, seeking a lazy/generic solution as opposed to other methods requiring ongoing upkeep if variable types change.