目前,如果我创建一个实现接口(interface)的类,创建的类将包含接口(interface)中未包含的所有方法。这是一个例子:
interface ExampleTypes {
alpha();
}
class Example implements ExampleTypes {
alpha () {
return true
}
beta () {
return true
}
}
我正在寻找一种方法来限制给定类可以拥有的方法。
这个我也试过:
class ExampleSource {
alpha () {
return true
}
}
class Example implements Partial<ExampleSource> {
alpha () {
return true
}
beta () {
return true
}
}
还有这个:
class ExampleSource {
alpha () {
return true
}
}
class Example implements ExampleSource {
alpha () {
return true
}
beta () {
return true
}
}
这是不直观的。我希望在 Example
中不允许使用 beta
。
这是有效的功能,但使用的是函数而不是类:
interface ExampleType {
alpha?();
beta?();
}
这是值(value):
function Example(): ExampleType {
return {
alpha: () => true,
};
}
这会引发 typescript 错误:
function Example(): ExampleType {
return {
alpha: () => true,
meow: () => true,
};
}
理想情况下,我可以拥有相同的功能,但需要使用类。
最佳答案
这是一个奇怪的请求,因为拥有额外的方法不会阻止您使用该类,就好像它们不存在一样。 TypeScript 并没有真正支持从类型中排除额外的属性或方法;也就是说,目前没有直接支持精确类型,如microsoft/TypeScript#12936 中所要求的那样.
幸运的是,您可以通过 making 获得这种行为 self 参照 conditional , mapped输入:
type Exactly<T, U> = { [K in keyof U]: K extends keyof T ? T[K] : never };
如果你声明一个类型 U
是Exactly<T, U>
,它将确保 U
火柴T
, 并且任何额外的属性都是 never
类型的.自引用/递归/循环类型并不总是编译,但在这种情况下,您只引用 keyof U
在 U
的定义中, 这是允许的。
让我们试试看:
interface ExampleTypes {
alpha(): boolean; // adding return type
}
// notice the self-reference here
class Example implements Exactly<ExampleTypes, Example> {
// okay
alpha() {
return true;
}
// error! Type '() => boolean' is not assignable to type 'never'.
beta() {
return true;
}
}
看起来有效!
关于javascript - 限制实现接口(interface)的 typescript 类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53674968/