26
loading...
This website collects cookies to deliver better user experience
// overload signature when argument
// value is of `string` type
// 👇 this is an overload signature 👇
function getLength(data: string): number;
// overload signature when argument
// value is of any `array` type
// 👇 this is also an overload signature 👇
function getLength(data: any[]): number;
// function that return the
// value of the `length` property
// 👇 this is the implementation signature 👇
function getLength(data: any): number {
return data.length;
}
// call the function with
// different argument value types
getLength("Hello World!"); // 12
getLength(["John", "Roy", "Lily"]); // 3
length
property associated with it.// function that return the
// value of the `length` property
function getLength(data: any): number {
return data.length;
}
length
property is available only to the string
and array
value types so let's try to make the function much more usable by writing 2
overload signatures above the original signature but without the function body part.string
type.// overload signature when argument
// value is of `string` type
function getLength(data: string): number;
// function that return the
// value of the `length` property
function getLength(data: any): number {
return data.length;
}
;
symbol (semi-colon).array
type.string
overload signature.// overload signature when argument
// value is of `string` type
// 👇 this is an overload signature 👇
function getLength(data: string): number;
// overload signature when argument
// value is of any `array` type
// 👇 this is also an overload signature 👇
function getLength(data: any[]): number;
// function that return the
// value of the `length` property
// 👇 this is the implementation signature 👇
function getLength(data: any): number {
return data.length;
}
data
has the type of any
is called the implementation signature
in TypeScript and this cannot be directly called by the user who is invoking the function.Implementation signatures
are there to associate with the function overloads parameters and thus functions overload signatures must also match the implementation signature.getLength
function with the value of a string
type and an array
type like this,// overload signature when argument
// value is of `string` type
// 👇 this is an overload signature 👇
function getLength(data: string): number;
// overload signature when argument
// value is of any `array` type
// 👇 this is also an overload signature 👇
function getLength(data: any[]): number;
// function that return the
// value of the `length` property
// 👇 this is the implementation signature 👇
function getLength(data: any): number {
return data.length;
}
// call the function with
// different argument value types
getLength("Hello World!"); // 12
getLength(["John", "Roy", "Lily"]); // 3
getLength
function are valid and are handled appropriately.VSCode
as your code editor it shows the various function call signatures available to the user if you hover the function.