Understanding types in TypeScript is fundamental to leveraging the language's static typing features. TypeScript provides a way to describe the shape and behavior of values, making it more robust and maintainable. Let's explore key concepts related to types in TypeScript:
- 1. Basic Types:
- 2. Object Types:
- 3. Union and Intersection Types:
- 4. Function Types:
- 5. Generics:
- 6. Type Aliases:
- 7. Type Assertion:
- 8. Declaration Files (.d.ts):
let age: number = 25;
let name: string = "Alice";
let isValid: boolean = true;
let numbers: number[] = [1, 2, 3];
let person: { name: string; age: number } = { name: "John", age: 30 };
interface Person {
name: string;
age: number;
}
let employee: Person = { name: "Alice", age: 25 };
let result: number | string = 10;
result = "Success";
type Name = { firstName: string };
type Age = { age: number };
let personInfo: Name & Age = { firstName: "John", age: 30 };
function add(x: number, y: number): number {
return x + y;
}
function identity<T>(value: T): T {
return value;
}
let result: number = identity(10);
type Point = { x: number; y: number };
let coordinates: Point = { x: 1, y: 2 };
let strLength: number = (<string>"Hello").length;
// example.d.ts
declare module "example-library" {
function myFunction(value: string): number;
}
Understanding these types and concepts allows you to create more expressive and error-resistant TypeScript code. TypeScript's static typing helps catch potential issues during development, making your codebase more robust and maintainable. Choose the appropriate type based on the context and requirements of your code.