字数
471 字
阅读时间
3 分钟
TypeScript: Documentation - Declaration Reference
常用声明
- 带有属性的对象(namespace
- 重载方法(function + function
- 接口(interface
- 类型别名(
type GreetingLike = string | (() => string) | MyGreeter;联合类型 - 类型嵌套
- class(class
- 全局变量(var、const 或 let
- 全局方法(function
type 和 interface
interface:接口,TS 设计出来主要用于定义【对象类型】,可以对【对象】的形状进行描述。
type :类型别名,为类型创建一个新名称。它并不是一个类型,只是一个别名。
类型别名可以起到类似接口的作用。但是,有一些细微的差别。主要区别在于 type 一旦定义就不能再添加新的属性,而 interface 总是可扩展
如果写库的时候,考虑到后续兼容性,可以优先使用一下 interface;在工作中,由于 interface 有默认合并,如果顾忌这方面,可以使用 type
interface 只能表示像对象那种结构的类型
type 可以动态计算属性,interface 没那么强大
ts
type Keys = "小王" | "小文"
type X = {
[key in Keys]: string
}
const test: X = {
'小王': '肌肉男',
'小文': '也是肌肉男'
}type 声明的类型不能重名,interface 声明的重命名会合并在一块
两者继承的方法不同
interface 使用 extends 继承
ts
interface IStateWithPop extends TState {
population: number;
}
复制代码type 可以使用 & 关键字
ts
type TStateWithPop = IState & { population: number; };但是 interface 不能继承一个联合类型,比如:
ts
type Input = {
a: string
};
type Output = {
b: string
};
type InputOrOutput = Input | Output
interface C extends InputOrOutput {
c: string
}