返回

TypeScript中函数/接口/类/泛型的语法精华大赏

前端

函数语法

TypeScript中的函数语法与JavaScript中的函数语法非常相似,函数的定义包括函数名、参数列表和函数体。函数类型可以被用作类型注解。可用于强制要求一个变量只接受一个有特定参数列表和返回值类型的函数。

例如:

function greet(name: string): string {
  return "Hello, " + name;
}

const hello = greet("TypeScript");

接口语法

接口是一种规范或契约,它定义了对象的结构和行为。接口可以帮助您在编写代码时更好地理解和组织对象。

interface Person {
  name: string;
  age: number;
}

const person: Person = {
  name: "TypeScript",
  age: 10
};

类语法

类是TypeScript中的一种数据结构,用于封装数据和行为。类可以继承自其他类,并可以包含属性、方法和构造函数。

class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, ${this.name}`);
  }
}

const person = new Person("TypeScript", 10);
person.greet();

泛型语法

泛型允许您在函数、接口或类中定义类型参数,以便它们可以与不同类型的数据一起使用。

function identity<T>(value: T): T {
  return value;
}

const number = identity(10);
const string = identity("TypeScript");

额外小知识点

  • 可选参数:可选参数必须在函数的必选参数之后,并放在函数的最后。
function greet(name?: string): string {
  return name ? "Hello, " + name : "Hello, world";
}

const hello = greet("TypeScript"); // "Hello, TypeScript"
const hello = greet(); // "Hello, world"
  • 动态成员:动态成员是指对象的成员在运行时才确定。动态成员通常存在于动态对象中,例如程序中的缓存对象。
const cache: { [key: string]: any } = {};

cache.foo = 10;
cache.bar = "TypeScript";
  • 继承:继承允许您创建一个类,该类从另一个类继承属性和方法。
class Animal {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, I am ${this.name}`);
  }
}

class Dog extends Animal {
  bark() {
    console.log("Woof!");
  }
}

const dog = new Dog("Spot");
dog.greet(); // "Hello, I am Spot"
dog.bark(); // "Woof!"
  • 多态:多态是指不同类型的对象可以具有相同的方法,但这些方法的具体实现可能有所不同。
abstract class Shape {
  abstract area(): number;
}

class Circle extends Shape {
  radius: number;

  constructor(radius: number) {
    super();
    this.radius = radius;
  }

  area(): number {
    return Math.PI * this.radius ** 2;
  }
}

class Rectangle extends Shape {
  width: number;
  height: number;

  constructor(width: number, height: number) {
    super();
    this.width = width;
    this.height = height;
  }

  area(): number {
    return this.width * this.height;
  }
}

const shapes: Shape[] = [
  new Circle(10),
  new Rectangle(5, 10)
];

for (const shape of shapes) {
  console.log(shape.area()); // "314.1592653589793" // "50"
}
  • 抽象类:抽象类是一种不能被实例化的类。抽象类用于定义一个类结构,而该类的具体实现由其子类来完成。
abstract class Shape {
  abstract area(): number;

  greet() {
    console.log("Hello, I am a shape");
  }
}

class Circle extends Shape {
  radius: number;

  constructor(radius: number) {
    super();
    this.radius = radius;
  }

  area(): number {
    return Math.PI * this.radius ** 2;
  }
}

const circle = new Circle(10);
circle.greet(); // "Hello, I am a shape"
circle.area(); // 314.1592653589793