Looking for a solution to receive the second calculated type in an overload method using TypeScript
type V1 = 'v1';
type V2 = 'v2';
type Versions = V1 | V2;
async analyze(test: 'v1', data: number): Promise<void>;
async analyze(test: 'v2', data: string): Promise<void>;
async analyze(test: Versions, data: string | number): Promise<void> {
switch (test) {
case 'v1':
return this.checkNumber(data); // data is number
case 'v2':
return this.checkString(data); // data is string
}
}
async checkString(data: string): Promise<void> {
console.log(data);
}
async checkNumber(data: number): Promise<void> {
console.log(data);
}
The current workaround involves adding conditional typing within the switch statement:
type Data<Type> = Type extends V1 ? number : string;
async analyze(test: 'v1', data: number): Promise<void>;
async analyze(test: 'v2', data: string): Promise<void>;
async analyze(test: Versions, data: Data<typeof test>): Promise<void> {
switch (test) {
case 'v1':
return this.checkNumber(data as Data<typeof test>); // data is number
case 'v2':
return this.checkString(data as Data<typeof test>); // data is string
}
}
Are there any alternative ways to achieve this?