menu

Function Overloading in TypeScript

Sometimes you encounter functions that return values ​​whose type depends on the parameters passed. For this, TypeScript uses function overloading. It allows you to specify different variants of function signatures.

Let's look at an example. Let's say we have a function that splits the characters of a string into an array of letters:

function splitStr(str: string): string[] { return str.split(''); }

Let's also have a function that splits the characters of a number into an array of digits:

function splitNum(num: number): number[] { let str: string = String(num); let arr: string[] = str.split(''); return arr.map(elem => +elem); }

Let's combine both functions into one. The new function should return either an array of numbers or an array of strings depending on the parameter type.

We use overloading to declare different signatures of our function:

function splitVal(val: number): number[]; function splitVal(val: string): string[] { // implementation of both signatures }

Now let's write the implementation of the function. In its code, we must determine by condition which of the function signatures worked, and depending on this, run the required code with the result of the required type:

function splitVal(val: number): number[]; function splitVal(val: string): string[] { if (typeof val === 'string') { return val.split(''); } else { let str: string = String(val); let arr: string[] = str.split(''); return arr.map((elem: string): number => +elem); } }

Unlike other languages, TypeScript creates a single function in an overload. You can't have multiple functions with the same name but different signatures.

Write a function that will return or change the text of a DOM element. It should work like this:

text('#elem', 'text'); // will set the text text('#elem'); // will return the current text
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline