Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 限制实现接口的typescript类方法_Javascript_Typescript_Class - Fatal编程技术网

Javascript 限制实现接口的typescript类方法

Javascript 限制实现接口的typescript类方法,javascript,typescript,class,Javascript,Typescript,Class,当前,如果我创建一个实现接口的类,那么创建的类将包含接口中未包含的所有方法。下面是一个例子: interface ExampleTypes { alpha(); } class Example implements ExampleTypes { alpha () { return true } beta () { return true } } 我正在寻找一种方法来限制给定类可以拥有的方法 这是我也尝试过的: class ExampleSource {

当前,如果我创建一个实现接口的类,那么创建的类将包含接口中未包含的所有方法。下面是一个例子:

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
  }
}
这是不直观的。我希望
示例中不允许
beta

这是使用函数而不是类工作的功能:

interface ExampleType {
  alpha?();
  beta?();
}
这就是价值:

function Example(): ExampleType {
  return {
    alpha: () => true,
  };
}
这会引发一个typescript错误:

function Example(): ExampleType {
  return {
    alpha: () => true,
    meow: () => true,
  };
}

理想情况下,我可以使用与类相同的功能。

这是一个奇怪的请求,因为有额外的方法不会阻止您使用类,就好像它们不存在一样。TypeScript实际上不太支持从类型中排除额外的属性或方法;也就是说,目前没有直接的支持

幸运的是,您可以通过一个自引用类型获得这种行为:


看起来很有效。希望有帮助。祝你好运

为什么??这不是OOP编程的工作方式,特别是考虑到坚实的原则。我想这是你可以在构造函数中做的事情。可能有一个类的给定实例应该符合的模型,并且让构造函数去掉所有不适合该模型的东西。这可以通过动态地传递表示类的函数/属性子集的不同模型来实现。TST中没有确切的类型,所以这通常是不可能的。允许使用额外的内容来满足类型要求。你为什么要这样做?@ThomasReggi:这些类没有额外的成员真的很重要吗?还是要限制这些类的使用?因为您可以通过向上转换到
Partial
来实现后者。但实际上试图限制一个类包含的方法是值得怀疑的。
function Example(): ExampleType {
  return {
    alpha: () => true,
    meow: () => true,
  };
}
type Exactly<T, U> = { [K in keyof U]: K extends keyof T ? T[K] : never };
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;
  }
}