当你浏览 collections typings file你经常看到这种模式:
interface Set<T> {
add(value: T): this;
clear(): void;
delete(value: T): boolean;
forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
readonly size: number;
}
interface SetConstructor {
new (): Set<any>;
new <T>(values?: T[]): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
即:
- 集合类型的接口(interface)
- 构造函数接口(interface)
- 和一个变量
declare
我真的无法理解这一点。有人可以回答一些问题吗?
Set<T>
的目的|很清楚,但实际执行在哪里?当我调用new Set()
我实际上创造了什么?在其他语言中,我无法实例化一个接口(interface)(它并不意味着被实例化),而只能实例化一个实现该接口(interface)的类。- 设置构造函数接口(interface)的目的是什么?它不是类,因此不代表可执行代码。
declare var
部分是这里最令人困惑的事情:-
declare
旨在引入一种在其他地方实现的类型。它如何用于变量?而且,不是import
(或require
)应该获取在别处实现的代码? - 它定义了一个与 Set 接口(interface)同名的变量。为什么这不会相互冲突?
- 它以某种方式“组合”了 2 个接口(interface)(名称为
Set
,类型为SetConstructor
),这让我摇头。那究竟是为了什么?
-
最佳答案
(1)
所有不同的 lib 文件都描述了已经存在于您将运行脚本的环境(浏览器/节点)中的 native 对象和类。
这就是为什么您看不到这些接口(interface)的实现的原因。
(2)
所有在 Constructor
后缀的接口(interface)都代表类的静态部分以及构造函数。
这两个(Set
和 SetConstructor
)共同代表了具有本地实现的 Set
类。
Set
接口(interface)描述实例,而 SetConstructor
表示类。
不同的构造函数方法(在 SetConstructor
中描述)返回 Set
,因此当您不实例化 Set
接口(interface)时,您会得到一个它的实例。
所有原生类型已经是环境的一部分,不需要导入 string
, Set
, Map
, promise
等
通过声明它们(使用 declare
关键字),您告诉编译器该变量在运行时就在那里。
(3)
您需要区分值和类型。
例如:
type MyPoint = {
x: number;
y: number;
}
const MyPoint: MyPoint = {
x: 0,
y: 0
}
这里 MyPoint
既是一个类型(接口(interface))又是一个值(const 变量),它们都有相同的名字,两者之间没有冲突,因为你从不使用名字作为既是变量又是类型。
请注意,例如,类既是类型又是值,因此您不能重复使用类名。
它并没有“结合”这两个接口(interface),实际情况是:
有一个名为 Set
的变量,它的类型是 SetConstructor
。
当您创建一个新实例 (new Set()
) 时,您将调用此 Set
变量中的方法之一,返回值的类型为 Set
(接口(interface))。
希望这能解决这个问题。
编辑
您应该将 Set
变量看成是这样的:
const MyClass = class {
constructor(public x: string) {}
}
本例中的Set
接口(interface)是:
interface MyClass {
x: string;
}
和SetConstructor
:
interface MyClassConstructor {
new (str: string): MyClass;
readonly prototype: MyClass;
}
唯一的区别是 Set
的实现是原生的。
关于typescript - 在 typescript 中接口(interface)和声明组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43659741/