Site icon JD Bots

How to Add a Type to a Function Parameter in TypeScript

A card titled Parameter Types, labelled TypeScript Basics, showing greet(name: string), the call greet(42) failing with TS2345, and greet(“Sam”) printing Hello, Sam!

Parameter Types: Tell TypeScript what a function expects.

In TypeScript, you write the type a function expects after each parameter: name: string. The TypeScript compiler, tsc, then checks every call and reports one that passes the wrong kind of value, before the code runs.

Every command and output on this page is real, run with Node.js 26.13.1 and TypeScript 7.0.2 on macOS.

Syntax

Syntax

function name(parameter: Type) {
  …
}

See Everyday Types in the TypeScript handbook, under Parameter Type Annotations.

Prerequisites

The Example

A greet function that expects a name as text, called once with a name and once, by mistake, with the number 42. The file is greet.ts.

Step 1: Write the Code

greet.ts

function greet(name: string) {
  return "Hello, " + name + "!";
}

console.log(greet("Sam"));
console.log(greet(42));

Step 2: Check It with tsc

Terminal

tsc --noEmit greet.ts

Output

greet.ts(6,19): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.

--noEmit tells tsc to check the code without writing JavaScript files. The error points at line 6, column 19: the number 42, which isn’t a string.

Step 3: Fix It

Remove the call with the number:

greet.ts

function greet(name: string) {
  return "Hello, " + name + "!";
}

console.log(greet("Sam"));

Step 4: Check It and Run It

Check it again. No output means tsc found no errors:

Terminal

tsc --noEmit greet.ts

Then run it:

Terminal

node greet.ts

Output

Hello, Sam!

Node.js removes the types and runs the code.

Common Mistakes

MistakeWhat happensDo this instead
Writing the type before the name: string nametsc reports error TS1005: ',' expected.Write the name, a colon, then the type: name: string
Running only nodeNode.js doesn’t check types, so the wrong call runs anywayRun tsc --noEmit first

FAQ

Why does node run the file even with the wrong call?

Node.js removes the types and runs the code without checking them. With the call greet(42) still in the file, node greet.ts printed Hello, 42!. Only tsc checks types.

Conclusion

Write parameter: Type on each parameter, and tsc --noEmit reports a call with the wrong kind of value before anyone runs the code.

Additional Resources

TypeScript, Node.js and other names mentioned are trademarks of their respective owners.

Exit mobile version