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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.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
带有泛型方法的Typescript接口_Typescript - Fatal编程技术网

带有泛型方法的Typescript接口

带有泛型方法的Typescript接口,typescript,Typescript,有没有可能在Typescript中有一个带有泛型方法的接口,让我们知道T type将扩展其他类型? interface Abc { a: string; b: string; c: string; } interface Checkout { onComplete<T>(session: T): void } class StripeCheckout implements Checkout { onComplete<T extends Abc>(abc

有没有可能在Typescript中有一个带有泛型方法的接口,让我们知道T type将扩展其他类型?

interface Abc {
  a: string;
  b: string;
  c: string;
}
interface Checkout {
  onComplete<T>(session: T): void
}
class StripeCheckout implements Checkout {
  onComplete<T extends Abc>(abc: T) {
    console.log(abc.a);
  }
}
用法示例:

const checkout = new StripeCheckout();
checkout.onComplete({a: '1', b: '2', c: '3'})

TypeScript和许多其他语言都不允许这样做,我建议第一种解决方案

接口Abc{
a:弦;
b:弦;
c:字符串;
}
接口默认值{
a:数字;
}
接口校验{
未完成(课时:T):无效;
其他功能(输入:A):作废;
}
类StripeCheckout实现签出{
otherFunction(输入:默认值){
抛出新错误(“方法未实现”);
}
完成(课程:Abc){
console.log(会话);
}
}

为什么??因为这样,您可以在
Checkout
界面上设置泛型的限制,从而提供更多的控制。你的接口应该定义契约,而不是实现契约的类。

签出有什么问题吗其中A、B、C、D是扩展方法的参数?你应该在接口级别定义约束,否则你就违反了替换原则
interface Abc {
  a: string;
  b: string;
  c: string;
}
interface Checkout<T> {
  onComplete(session: T): void
}
class StripeCheckout implements Checkout<Abc> {
  onComplete(session: Abc) {
    console.log(session);
  }
}
interface Abc {
  a: string;
  b: string;
  c: string;
}
interface Checkout {
  onComplete(session: any): void
}
class StripeCheckout implements Checkout {
  onComplete(session: Abc) {
    console.log(session);
  }
}
const checkout = new StripeCheckout();
checkout.onComplete({a: '1', b: '2', c: '3'})