类型别名 - type

我们通过直接在类型注解中编写对象类型和联合类型来使用它们。 这很方便,但是常常会想要多次使用同一个类型,并且通过一个名称引用它。

类型别名 正是如此 - 任意 类型 的一个 名称 。 类型别名的语法是:

type Point = {
  x: number;
  y: number;
};
 
// 与前面的示例完全相同
function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
 
printCoord({ x: 100, y: 100 });

实际上,不只是对象类型,你可以使用类型别名为任何类型命名。 例如,类型别名可以命名联合类型:

type ID = number | string;

请注意,别名 只是 别名 - 你不能使用类型别名创建同一类型的不同“版本”。 当你使用别名时,它与您编写的别名类型完全一样。 换句话说,这段代码 看起来 可能是非法的,但是对于 TypeScript 来说是正确的,因为这两种类型都是同一类型的别名:

declare function getInput(): string;
declare function sanitize(str: string): string;
// ---分割---
type UserInputSanitizedString = string;
 
function sanitizeInput(str: string): UserInputSanitizedString {
  return sanitize(str);
}
 
// 创建一个经过清理的输入框
let userInput = sanitizeInput(getInput());
 
// 仍然可以使用字符串重新赋值
userInput = "new input";

最后userInput被赋值的只是一个 string 的别名,因此,新赋值的 string 是合法的

接口 - interface

接口声明 是命名对象类型的另一种方式:

interface Point {
  x: number;
  y: number;
}
 
function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
 
printCoord({ x: 100, y: 100 });

就像我们上面使用类型别名时一样,这个示例的工作方式就像我们使用了匿名对象类型一样。 TypeScript 只关心我们传递给 printCoord 的值的结构 - 它只关心它是否具有预期的属性。 只关心类型的结构和功能,这就是为什么我们说 TypeScript 是一个 结构化类型 的类型系统。

interface 的重合

当两个interface发生重名时,即定义了两个相同名字的interface,其会合并内部所有的属性

interface UserType {
    studentID: number
    password: number
}

interface UserType {
    isIkun: true
}

let obj: UserType = {
    studentID: 2021050919079,
    password: 281733
} // 缺少了isIkun

此时,UserType类型会多出来一个 isIkun? 的属性

索引签名 - 任意key

有时后端接口可能会返回一些额外的数据,这时,我们可以将多余的数据进行统一定义,ts将不再检查其类型

interface UserType {
	name: string
	age: number
	[propName: string]: any
}