String Literal and Overload Function
In this lesson, we will approach the string literal with an overload function.
We'll cover the following
A parameter with a string literal
A function can use a string literal as its parameter to know which return type is possible. For example, it’s possible to have a function with a string parameter and have many overloads where a specific string value will cause the execution of one function or another.
In the example below, the method accepts only the strings, "batman"
and "superman"
, even if the signature shows a string. See lines 12 and 13. TypeScript unites both overloads to create a string literal of all the overloads.
For example, if you are using an IDE that supports TypeScript, the IDE will show the return type, Batman
if the parameter is "batman"
. Line 14 combines all the overload.
Get hands-on with 1400+ tech skills courses.