Design a site like this with
Get started

Type Polymorphic Functions In TypeScript

JavaScript allows functions to work flexibly when the arguments passed are of different types and/or at different positions:

  • The useState Hook lets you pass an initial value or a function for lazy initialization, or you can skip it altogether and pass nothing to it.
  • The query API from node-postgres accepts an optional callback function and returns a promise when the callback function isn’t provided.
  • The write function of the file system API in Node.js defines the first argument to be either a buffer of data or a string that we write to a file.
  • The extend API from the package node-extend enables deep copying by allowing you to pass an optional boolean flag as the first argument to the function call.

It’s been a running theme in my TypeScript career: I have to create and type functions like these, and I’ve definitely struggled. But, I’ve found a few solutions that have worked for me. In this post, I’ll walk you through some techniques I use to type polymorphic functions more easily.

Read more…


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: