Trying to figure out how to overload a function in TypeScript so it can determine the type of arg2 based on the value of arg1. Arg1 has a list of known values.
Here's a rough example of what I'm attempting:
interface CatArgs {legs : number}
interface FishArgs {fins: number}
type CarOrFishArgs = CatArgs | FishArgs;
type Animal = Cat | Fish;
type Type = 'Cat' | 'Fish';
class Cat{
constructor(args:CatArgs){}
}
class Fish {
constructor(args:FishArgs){}
}
export declare function getAnimal(type:'Cat', args:CatArgs): Cat;
export declare function getAnimal(type:'Fish', args:FishArgs): Fish;
export function getAnimal(type:Type, args:CarOrFishArgs): Animal {
switch (type) {
case 'Cat':
return new Cat(args as CatArgs);
case 'Fish':
return new Fish(args as FishArgs);
}
}
Encountering an error message stating "Overload signatures must all be ambient or non-ambient". Are these kinds of features supported by TypeScript? What could be the issue here?