Here is an example of the function overloading which is published on the official website :
let suits = ["hearts", "spades", "clubs", "diamonds"];
function pickCard(x: {suit: string; card: number; }[]): number;
function pickCard(x: number): {suit: string; card: number; };
function pickCard(x): any {
// Check to see if we're working with an object/array
// if so, they gave us the deck and we'll pick the card
if (typeof x == "object") {
let pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
// Otherwise just let them pick the card
else if (typeof x == "number") {
let pickedSuit = Math.floor(x / 13);
return { suit: suits[pickedSuit], card: x % 13 };
}
}
When I put this code to my working typscript file i get error:
Error:(5, 19) TS7006:Parameter 'x' implicitly has an 'any' type.
How to make this example to work?
That's because you probably have the noImplicitAny flag on.
In this case you can either do:
function pickCard(x: any): any {
...
}
Or:
function pickCard(x: number | {suit: string; card: number; }[]): any {
...
}
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