在 TypeScript 中,类型声明可以通过以下方式进行:

  1. 使用变量和函数的类型注释

例如:

let myNumber: number = 10;
function addNumbers(a: number, b: number): number {
  return a + b;
}
  1. 使用接口进行类型声明

例如:

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

let person: Person = {
  name: "Alice",
  age: 30
};
  1. 使用类进行类型声明

例如:

class Car {
  brand: string;
  model: string;
  year: number;

  constructor(brand: string, model: string, year: number) {
    this.brand = brand;
    this.model = model;
    this.year = year;
  }
}

let myCar: Car = new Car("Toyota", "Camry", 2020);
  1. 使用类型别名进行类型声明

例如:

type MyString = string | null | undefined;

let myString: MyString = "Hello";
let myNull: MyString = null;
let myUndefined: MyString = undefined;
  1. 使用枚举进行类型声明

例如:

enum Color {
  Red,
  Green,
  Blue
}

let myColor: Color = Color.Red;
ts类型声明怎么做

原文地址: https://www.cveoy.top/t/topic/Mej 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录