The use of types is a fundamental aspect of the language, and it's one of the key features that differentiates TypeScript from JavaScript.
- 1. Type Annotations:
- 2. Function Parameters and Return Types:
- 3. Interfaces:
- 4. Arrays and Generics:
- 5. Union and Intersection Types:
- 6. Type Aliases:
- 7. Enums:
- 8. Classes:
- 9. Type Assertion:
- 10. Declaration Files (.d.ts):
-
You can explicitly declare the type of a variable using type annotations. For example:
let name: string = "John"; let age: number = 25;
-
Specify the types of function parameters and return values:
function add(x: number, y: number): number { return x + y; }
-
Use interfaces to define the shape of objects:
interface Person { name: string; age: number; } let person: Person = { name: "Alice", age: 30 };
-
Use generics to create reusable components with dynamic types:
let numbers: Array<number> = [1, 2, 3, 4];
-
Combine types using unions or intersections:
type Status = "success" | "error"; type Result = { value: number } & { message: string };
-
Create your own custom types with type aliases:
type Point = { x: number; y: number; };
-
Use enums to define a set of named constants:
enum Color { Red, Green, Blue } let myColor: Color = Color.Green;
-
Define classes with typed properties and methods:
class Dog { name: string; constructor(name: string) { this.name = name; } bark(): void { console.log("Woof!"); } } let myDog: Dog = new Dog("Buddy");
-
Use type assertion to explicitly specify a type when TypeScript cannot infer it:
let myVariable: any = "Hello, TypeScript!"; let stringLength: number = (myVariable as string).length;
-
Use declaration files to provide type information for external libraries or JavaScript code:
// example.d.ts declare module "example-library" { function myFunction(value: string): number; }
These are just a few examples of how you can use types in TypeScript. Types provide a powerful way to catch errors early in the development process, improve code documentation, and enable better tooling support in modern development environments.