typescript
/

TypeScript Functions

Last Sync: Today

On this page

11
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

typescript

TypeScript Functions

What are Functions?

Functions in TypeScript are blocks of reusable code with optional type annotations for parameters and return values.

Basic Function

TypeScriptRead-only
1
function add(a: number, b: number): number {
  return a + b;
}

Void Function

TypeScriptRead-only
1
function logMessage(msg: string): void {
  console.log(msg);
}

Optional Parameters

TypeScriptRead-only
1
function greet(name?: string) {
  return name || 'Guest';
}

Default Parameters

TypeScriptRead-only
1
function greet(name: string = 'Guest') {
  return name;
}

Arrow Functions

TypeScriptRead-only
1
const multiply = (a: number, b: number): number => a * b;

Function Types

TypeScriptRead-only
1
let addFn: (a: number, b: number) => number;
addFn = add;

Rest Parameters

TypeScriptRead-only
1
function sum(...nums: number[]): number {
  return nums.reduce((a, b) => a + b, 0);
}

Best Practices

  • Always define parameter types
  • Specify return types for clarity
  • Use default parameters when needed
  • Keep functions small and reusable

Common Mistakes

  • Not specifying return types
  • Incorrect parameter types
  • Overusing any type
  • Complex functions without structure

Conclusion

TypeScript functions improve code reliability by enforcing types for parameters and return values, ensuring safer and predictable behavior.

Try it yourself

function add(a: number, b: number): number {
  return a + b;
}

Test Your Knowledge

Q1
of 3

Return type defined by?

A
=
B
:
C
->
D
::
Q2
of 3

Optional parameter symbol?

A
!
B
*
C
?
D
#
Q3
of 3

Void means?

A
Number
B
String
C
No return
D
Any

Frequently Asked Questions

What is return type?

The type of value returned by a function.

What is optional parameter?

A parameter that may or may not be passed.

What is void?

Function returns no value.

Previous

ts type inference

Next

ts function types

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.