Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I export an overloaded function in typescript

Tags:

typescript

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?

like image 882
AriehGlazer Avatar asked Feb 22 '26 17:02

AriehGlazer


1 Answers

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);
    }
}
like image 141
lukasgeiter Avatar answered Feb 25 '26 18:02

lukasgeiter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!