TypeScript 与 JavaScript 之间存在一种不同寻常的关系。TypeScript 提供了 JavaScript 的所有特性,以及在这些特性之上的一个附加层: TypeScript 的类型系统

例如,JavaScript 提供了诸如 string 和 number 这样的原始类型,但它不检查你在赋值时与类型是否匹配。TypeScript 提供了这样的功能。

类型推断 - Type by Inference

TypeScript 可以识别 JavaScript 语言,在许多情况下可以推断类型。例如,在创建变量并将其赋值给特定值时, TypeScript 将使用该值作为其类型。

let helloWorld = "Hello World";
        
let helloWorld: string

通过感知 JavaScript 的工作原理,TypeScript 可以构建一个接受 JavaScript 代码但具有类型的类型系统。这个类型系统使得我们不需要添加额外的字符来显式地指定类型。在上面的例子中,TypeScript就是这样知道 helloWorld 是 string 类型的。

定义类型

你可以在 JavaScript 中使用各种各样的设计模式。然而,某些设计模式使得类型难以自动推断(例如,使用动态编程的模式)。为了使类型推断涵盖这些情况, TypeScript 支持扩展 JavaScript 语言,它可以让 TypeScript 知道如何去推断类型。

例如,要创建具有推断类型的对象,该类型包括 name: string 和 id: number,你可以这么写:

const user = {
  name: "Hayes",
  id: 0,
};

你可以使用 interface 关键字声明显式地描述此对象的内部数据的类型(译者注:下文可能译为“结构”):

interface User {
  name: string;
  id: number;
}

然后你可以声明一个符合此接口(interface)的 JavaScript 对象,在变量声明后使用像 : TypeName 这样的语法:

interface User {
  name: string;
  id: number;
}

const user: User = {
  name: "Hayes",
  id: 0,
};

如果提供的对象与提供的接口不匹配,TypeScript 将警告:

interface User {
  name: string;
  id: number;
}
 
const user: User = {
  username: "Hayes",
Type '{ username: string; id: number; }' is not assignable to type 'User'.
  Object literal may only specify known properties, and 'username' does not exist in type 'User'.
  id: 0,
};

由于 JavaScript 支持类和面向对象编程,TypeScript 也支持。你可以将接口声明与类一起使用:

interface User {
  name: string;
  id: number;
}
 
class UserAccount {
  name: string;
  id: number;
 
  constructor(name: string, id: number) {
    this.name = name;
    this.id = id;
  }
}
 
const user: User = new UserAccount("Murphy", 1);

您可以使用接口对参数进行注释,并将值返回给函数:

interface User {
  name: string;
  id: number;
}
// ---分割线---
function getAdminUser(): User {
  //...
}
 
function deleteUser(user: User) {
  // ...
}