Functions as types
As those familiar with JavaScript will know, functions themselves are values, and therefore, they have a type.
Let's take two functions, multiply
and echoString
as examples:
function multiply(x: number, y: number): number {
return x * y;
}
function echoString(input: string): string {
return input;
}
We then declare our function type definitions using the following syntax:
let myMultiply: (val1: number, val2: number) => number;
let myEchoString: (val: string) => string;
// Sanity check
myEchoString = echoString; // OK
myMultiply = echoString; // Error: type '(input: string) => string' is not assignable to type '(val1: number, val2: number) => number'
Last updated