Type annotations in TypeScript are a way of explicitly specifying the data type of a variable, function parameter, return value, or any other TypeScript entity. Type annotations help the TypeScript compiler catch type-related errors during development, ensuring more robust and maintainable code. Here's an overview of type annotations in TypeScript:
1. Basic Type Annotations:
Variables:
let num: number = 10;
let str: string = "Hello";
let bool: boolean = true;
Function Parameters:
function greet(name: string): void {
console.log("Hello, " + name);
}
Return Types:
function add(a: number, b: number): number {
return a + b;
}
2. Arrays and Objects:
Arrays:
let numbers: number[] = [1, 2, 3];
let names: string[] = ["John", "Jane", "Doe"];
Objects:
let person: { name: string, age: number } = { name: "John", age: 30 };
3. Interfaces:
interface Person {
name: string;
age: number;
}
let john: Person = { name: "John", age: 30 };
4. Union Types:
let value: string | number;
value = "Hello";
value = 10;
5. Type Aliases:
type Point = { x: number, y: number };
function getDistance(point1: Point, point2: Point): number {
// Calculate distance
}
let origin: Point = { x: 0, y: 0 };
6. Function Types:
type MathOperation = (a: number, b: number) => number;
let add: MathOperation = function(x, y) {
return x + y;
};
7. Type Assertion:
let value: any = "Hello";
let length: number = (value as string).length;
8. Built-in Types:
let date: Date = new Date();
let regex: RegExp = /[a-zA-Z]+/;
9. Void and Never:
function logMessage(message: string): void {
console.log(message);
}
function throwError(message: string): never {
throw new Error(message);
}
These are some examples of type annotations in TypeScript. By using type annotations effectively, developers can improve the clarity, correctness, and maintainability of their code.
0 Comments