Typescript Type Annotations
Learn how to specify types for variables, function parameters, and return values.
In TypeScript, type annotations allow you to specify types for variables, function parameters, and return values, which improves code readability and catches potential errors. Here’s a breakdown of how to use them:
1. Variable Type Annotations
You can define the type of a variable by using a colon (:
) followed by the type after the variable name.
let username: string = "Amir";let age: number = 30;let isDeveloper: boolean = true;
In this example:
username
is astring
.age
is anumber
.isDeveloper
is aboolean
.
If you try to assign a different type to these variables, TypeScript will throw an error.
2. Function Parameter Type Annotations
You can specify types for each parameter in a function, ensuring that only the correct types can be passed.
function greet(name: string, age: number): string {return `Hello, ${name}. You are ${age} years old.`;}
Here:
name
must be astring
.age
must be anumber
.
If you pass a different type to name
or age
, TypeScript will give an error.
3. Function Return Type Annotations
You can specify the type of value a function should return by adding a type annotation after the parameter list.
function add(a: number, b: number): number {return a + b;}
In this example:
The function
add
takes two parameters,a
andb
, both of typenumber
.The return type of
add
is also specified asnumber
.
If you return a non-number
value from this function, TypeScript will throw an error.
4. Optional and Default Parameters
You can mark a parameter as optional by adding a question mark (?
) after the parameter name, or provide a default value. Optional parameters have a type of type | undefined
.
function greetUser(name: string, title?: string): string {return title ? `${title} ${name}` : `Hello, ${name}`;}function logMessage(message: string = "No message provided"): void {console.log(message);}
In greetUser
:
title
is optional; if it’s not provided, it will beundefined
.
In logMessage
:
message
has a default value and does not require an argument.
By using type annotations, TypeScript ensures you write consistent and reliable code, reducing runtime errors.