I have a function that I want to overload, so that it knows the type of arg2 based on the value of arg1 (which has a list of know values).
A very rough example to demonstrate what I'm trying to do:
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);
}
}
But I'm getting "Overload signatures must all be ambient or non-ambient".
Is this type of feature supported by TypeScript? What am I doing wrong?
To specify overload signatures you don't need declare:
export function getAnimal(type:'Cat', args:CatArgs): Cat;
export 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With