惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
D
Docker
GbyAI
GbyAI
B
Blog RSS Feed
博客园 - 司徒正美
博客园 - Franky
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
C
Check Point Blog
IT之家
IT之家
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
AI
AI
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
S
Secure Thoughts
博客园 - 聂微东
L
LINUX DO - 最新话题
U
Unit 42
SecWiki News
SecWiki News
A
Arctic Wolf
Schneier on Security
Schneier on Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Visual Studio Blog
量子位
The Cloudflare Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
大猫的无限游戏
大猫的无限游戏
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
B
Blog
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
Scott Helme
Scott Helme
Last Week in AI
Last Week in AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
Latest news
Latest news

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
TypeScript Function Types: A Beginner's Guide
Dmitri Pavlutin · 2023-03-28 · via Dmitri Pavlutin Blog

Functions are the small pieces of logic that together form applications. If you write applications in TypeScript, understanding function types is a must.

This guide covers everything you need to know to get started with TypeScript function types.

Table of Contents

  • 1. TypeScript function type
  • 2. TypeScript function type guide
  • 3. TypeScript method type
  • 4. TypeScript function interface
  • 5. Conclusion

1. TypeScript function type

Functions in JavaScript/TypeScript are first-class objects. You can assign functions to variables, use functions as arguments to other functions, and even return functions.

Knowing how to type functions in TypeScript is a must if you want to pass functions around as objects.

Let's start with a simple case: a function that sums 2 numbers.

Here's the function in plain JavaScript:


// JavaScript

function sum(a, b) {

return a + b

}


sum() is a function that returns the sum of the parameters a and b.

In plain JavaScript, you know that the parameters a and b must be numbers, and the returned value must also be a number.


// JavaScript

function sum(a, b) {

return a + b

}

console.log(sum(4, 3)); // logs 7


In the example above the arguments 4 and 3, as well as the returned value 7 are all numbers.

Now that you have the parameter and return type information, you can easily translate this into a TypeScript function type of the sum():


// TypeScript function type

(a: number, b: number) => number


(a: number, b: number) is the part that specifies the parameters and their types. After the fat arrow indicate the return type: => number. That's it.

(Note: the function type looks similar to an arrow function. But they are different things.)

Because of their length, working with function types is more convenient if you store them into a type alias. An alias allows the type to be reused in multiple places:


// Sum is a type alias

type Sum = (a: number, b: number) => number


Having the Sum type, you can use it to annotate any place where the function object is passed around.

TypeScript function type

The first thing you can do, of course, is to assign the function to a variable:


type Sum = (a: number, b: number) => number

// Assign to variable

const sum1: Sum = function(a: number, b: number): number { return a + b } // OK

const sum2: Sum = function(a, b) { return a + b } // OK


Open the demo.

In the example above sum1 and sum2 are of type Sum.

sum2 function doesn't have the parameter and return types indicated: this is because TypeScript infers these types from the Sum.

I recommend using type inference in your code to avoid repetition, e.g. label your functions as I did with sum2 instead of sum1. In the following examples I'm going to use type inference.

In case of a higher-order function, you use the function object as an argument or even return it from another function:


type Sum = (a: number, b: number) => number

// Sum as argument

function someFunc1(func: Sum): void {

func(1, 2)

}

someFunc1((a, b) => a + b) // OK

// Sum returned

function someFunc2(): Sum {

return (a, b) => a + b

}

someFunc2()(1, 2) // OK


Open the demo.

2. TypeScript function type guide

To help you better understand how to use the function types, let's look at some guiding ideas.

1) Use ? to indicate an optional parameter:


type SumOpt = (a: number, b?: number) => number

const sumOpt: SumOpt = function sum(a, b) {

if (b === undefined) {

return a

}

return a + b

}

sumOpt(2) // OK


Open the demo.

b? in SumOpt function type is an optional parameter. The second argument can be omitted when invoking sumOpt(2).

2) A rest parameter is typed using the three dots and an array type:


type SumRest = (...numbers: number[]) => number

const sumRest: SumRest = function sum(...numbers) {

return numbers.reduce((sum, number) => sum + number)

}

sumRest(1, 2) // OK


Open the demo.

...numbers: number[] inside of the function type indicates a rest parameter.

3) The regular and the arrow functions have the same type:


type Sum = (a: number, b: number) => number

const regularFunc: Sum = function(a, b) { return a + b } // OK

const arrowFunc: Sum = (a, b) => a + b // OK


Open the demo.

regularFunc is a regular function and arrowFunc is an arrow function. Both are Sum types.

4) The parameter names in the function type and the function instance can be different:


type Sum = (a: number, b: number) => number

const sumDiffParam: Sum = function(n1, n2) { return n1 + n2 } // OK


Open the demo.

It's acceptable for the function type to have the parameter names a and b, but the function instance parameters n1 and n2.

5) The function instance can have fewer parameters than the function type:


type Sum = (a: number, b: number) => number

const sumShort: Sum = function (a) { return a } // OK

const sumShorter: Sum = function () { return 0 } // OK


Open the demo.

sumShort and sumShorter have fewer parameters than the type Sum but are still of type Sum.

However, the function instance cannot have more parameters than the function type:


type Sum = (a: number, b: number) => number

const sumLonger: Sum = function (a, b, c) { return a + b + c } // Type error!


Open the demo.

6) The return type of an async function must be a promise Promise<T>:


type SumAsync = (a: number, b: number) => Promise<number>

const sumAsync: SumAsync = async function (a, b) {

return await a + b

} // OK


Open the demo.

sumAsync is an async function. The return type of an async function must be a promisePromise<T> type (which is a generic type).

3. TypeScript method type

A method is a function that exists and is executed in the context of an object. Method types in TypeScript have to exist within the object type.

You can define methods on interfaces:


interface ObjectWithMethod {

sum(a: number, b: number): number

}


or even use a type alias:


type ObjectWithMethod = {

sum(a: number, b: number): number

}


ObjectWithMethod is an object type having a method sum(). The first and second parameter types (a: number, b: number) are numbers, and the return type : number is also a number.

TypeScript Method Type

Note an important difference. The function type uses the fat arrow => to separate the parameter list from the return type, while the method type uses the colon :.

Let's look at a method type example:


interface ObjectWithMethod {

sum(a: number, b: number): number

}

const object: ObjectWithMethod = { // OK

sum(a, b) { return a + b }

}


Open the demo.

object is of type ObjectWithMethod and contains a method sum().

Of course, you can add many method types to an object type:


interface ObjectWithMethod {

sum(a: number, b: number): number

product(a: number, b: number): number

abs(a: number): number

// etc...

}


4. TypeScript function interface

Another interesting way of writing a function type is to use a TypeScript function interface. It's also called function call signature (too scientific for me).

The function interface looks similar to an object interface with a method. But the function interface doesn't have the method name written:


interface SumInterface {

(a: number, b: number): number

}


SumInterface is a function interface. Note that before the expression (a: number, b: number): number there is no method name indicated.

Let's use SumInterface to annotate a variable:


interface SumInterface {

(a: number, b: number): number

}

const sum: SumInterface = function(a, b) { return a + b } // OK


Open the demo.

Most of the time you will use the regular TypeScript function type (a: number, b: number) => number instead of a function interface. Mostly because a function type is shorter to write.

But you can benefit from the function interface when you want to add properties to the function object. Let's add the property description to the function interface:


interface SumWithDescription {

(a: number, b: number): number

description: string

}

const sum: SumWithDescription = function(a, b) {

return a + b

}

sum.description = 'A function that sums two numbers'


Open the demo.

SumWithDescription, in addition to being a function, also has a description property of type string.

TypeScript function interface

5. Conclusion

Writing a function type is simple:


type Sum = (a: number, b: number) => number


Specify the parameter types in a pair of parentheses, put the fat arrow =>, and the return type.

For methods, you have to define the method on an object type:


interface ObjectWithMethod {

sum(a: number, b: number): number

}


Again, put the parameters into a pair of parentheses, then a colon : and finally indicate the return type.

Now you should be able to type functions in your TypeScript code.

How can you type a function that can be invoked in multiple ways? Follow the TypeScript Function Overloading post for more information.

Have any questions about function types? Leave a comment and let's discuss!