How to add a number type annotation to a function parameter in TypeScript?

September 9, 2021 - 2 min read

Number type annotations can be added to function parameters by declaring the function and then adding the name of the parameter followed by the : symbol (colon) and then the type number after the symbol.

TL;DR

// add number type annotation
// to the parameter num
function add100(num: number) {
  return num + 100;
}

// call the function
add100(100); // ✅ allowed

For example, let's say we have a function called add100 and on calling the function adds the number 100 with the value we supplied as the argument.

So to get the number we can use a parameter called num. It can be done like this,

// a simple function
function add100(num) {
  return num + 100;
}

Now we need to only allow number type values as the value for the parameter num. To do that we can add a number type annotation to the function parameter. In our case, the parameter is num.

It can be done like this,

// add number type annotation to
// the parameter num
function add100(num: number) {
  return num + 100;
}

Now let's try to call the function add100 and then pass a number value as an argument to the function like this,

// add number type annotation
// to the parameter num
function add100(num: number) {
  return num + 100;
}

// call the function
add100(100); // ✅ allowed

As you can see from the above code TypeScript allowed us to pass the number value of 100 to the function parameter num since the allowed type for the num function parameter is a number.

Now let's try to pass another value of string type Hello! to the num function parameter to see what happens,

// add number type annotation
// to the parameter num
function add100(num: number) {
  return num + 100;
}

// call the function
add100(100); // ✅ allowed
add100("Hello"); // ❌ not allowed. Argument of type 'string' is not assignable to parameter of type 'number'.

As you can see that the TypeScript will throw an error saying that the Argument of type 'string' is not assignable to parameter of type 'number'. which is also what we want to happen.

See the above codes live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.