1. 类型注解
TypeScript 是一种静态类型检查的语言,可以为变量、函数参数、函数返回值等添加类型注解:
let age: number = 20; function add(a: number, b: number): number { return a + b; }
2. 接口
TypeScript 支持使用接口来定义类、函数、对象的结构,可以提高代码的可读性和可维护性:
interface Person { name: string; age: number; sayHi: () => void; } class Student implements Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } sayHi() { console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`); }
3. 类和继承
TypeScript 支持类和继承,可以使用 class
关键字来定义类:
class Animal { name: string; constructor(name: string) { this.name = name; } move(distance: number) { console.log(`${this.name} moved ${distance}m.`); } } class Dog extends Animal { bark() { console.log('Bark bark!'); } } const dog = new Dog('Buddy'); dog.move(10); // Buddy moved 10m. dog.bark(); // Bark bark!
4. 枚举
TypeScript 支持枚举类型,可以使用 enum
关键字来定义枚举类型:
enum Color { Red, Green, Blue } let c: Color = Color.Green; console.log(c); // 1 enum Direction { Up = 'UP', Down = 'DOWN', Left = 'LEFT', Right = 'RIGHT' } let d: Direction = Direction.Up; console.log(d); // UP
5. 泛型
TypeScript 支持泛型编程,可以编写更加通用和灵活的代码:
function identity<T>(arg: T): T { return arg; } console.log(identity<string>('hello')); // hello console.log(identity<number>(123)); // 123