TypeScript Functions

What are Functions?

A function is a block of code that runs when called.

In TypeScript, functions can include types for parameters and return values.

Basic Function

Loading...
Output:

Parameter Types

You can define types for function parameters.

Loading...
Output:

Return Types

Functions can specify the type of value they return.

Loading...
Output:

Arrow Functions

Arrow functions support type annotations.

Loading...
Output:

Optional Parameters

Use ? to make parameters optional.

Loading...
Output:

Default Parameters

Loading...
Output:

Function Types

You can define types for entire functions.

Loading...
Output:

Full Example

Loading...
Output:

Why Functions are Important

  • Reuse code
  • Enforce type safety
  • Improve readability
  • Reduce bugs

Common Mistakes

  • Forgetting return types
  • Using incorrect parameter types
  • Confusing optional and default parameters

Practice

Create a function that takes two numbers and returns their product.

Loading...
Output:

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic