Skip to main content

Function types

Like JavaScript, functions in TypeScript can be named or anonymous. This allows you to choose the most convenient approach for developing your application, whether it is building a list of functions in the API, or nesting one function within another. ...

Function type#

Each function has a type, just like regular variables. A function type actually represents a combination of parameter types and return types. For example, take the following function:

function sum(x: number, y: number): number {
return x + y
}

It is of type (x: number, y: number) => number;, that is, it takes two number parameters and returns a value of type number. Parameter names in a function type do not have to match the names of a specific function. The return type is preceded by an equal sign with an arrow.

And just like defining variables of a specific type, you can define variables that have a function type:

let op: (x: number, y: number) => number

That is, the variable op represents any function that takes two numbers and returns a number. For example:

function sum(x: number, y: number): number {
return x + y
}
function subtract(a: number, b: number): number {
return a - b
}
let op: (x: number, y: number) => number
op = sum
console.log(op(2, 4)) // Работает как сложение = 6
op = subtract
console.log(op(6, 4)) // Сейчас как вычитание = 2

Here, at the beginning, the variable op points to the functionsum.And accordingly, calling op (2, 4) will actually represent a call to sum (2, 4). And then op points to a function subtract.

Payment#

Now you are on a stripped-down version of the site, after subscribing to Patreon, you will get full access to the training course, as well as access to our server's private channels in Discord.

Download our mobile application or get tested in our JavaScript telegram bot, and also subscribe to our news.

Become a Patron!

Sumerian school

Contributors ✨#

Thanks goes to these wonderful people (emoji key):


Dmitriy K.

📖

Dmitriy Vasilev

💵

Resoner2005

🐛 🎨 🖋

Navernoss

🖋 🐛 🎨

Become a Patron!