How to assign properties to a Function in TypeScript

avatar

Borislav Hadzhiev

Sun Feb 27 20222 min read

banner

Photo by Brooke Cagle

Assign properties to a Function in TypeScript #

To assign properties to a function declare the function and use dot notation to assign a property to it, e.g. myFunction.myProperty = myValue. TypeScript allows us to define properties on functions simply by assigning the properties in the same scope.

index.ts
function doMath(a: number, b: number) { return a + b; } // ✅ Add method on function doMath.multiply = (a: number, b: number) => { return a * b; }; console.log(doMath.multiply(10, 5)); // 👉️ 50 // ✅ Add property to function doMath.defaultProps = { num1: 5, num2: 701, }; console.log(doMath.defaultProps); // 👉️ {num1: 5, num2: 701}

TypeScript allows us to assign properties and methods to functions by default, as long as we do it in the same scope.

In the code snippet above, we assigned a multiply method on the doMath function without having to type anything explicitly.

However, note that the assignment has to be in scope of the function declaration.

The second example shows how to assign a property to the function.

This syntax is supported for both named and arrow functions. Here is the same example using arrow functions.

index.ts
/** * 👇️ const doMath: { (a: number, b: number): number; multiply(a: number, b: number): number; defaultProps: { num1: number; num2: number; }; } */ const doMath = (a: number, b: number) => { return a + b; }; // ✅ Add method on function doMath.multiply = (a: number, b: number) => { return a * b; }; console.log(doMath.multiply(10, 5)); // 👉️ 50 // ✅ Add property to function doMath.defaultProps = { num1: 5, num2: 701, }; console.log(doMath.defaultProps); // 👉️ {num1: 5, num2: 701}

You can hover over the doMath function in your IDE to look at its type.

The ability to assign properties an methods on functions by default was introduced in TypeScript 3.1 to make it easier to convert JavaScript to TypeScript code.

This also enables us to use common patterns like defaultProps in React.js.

index.tsx
const MyComponent = ({ num }) => <h1>Number is {num}</h1>; MyComponent.defaultProps = { num: 701, };
Use the search field on my Home Page to filter through my more than 1,000 articles.