如何在 Typescript 接口中引用 self 的类型(对于 IClonable 接口) [英] How to reference type of self in Typescript interface (for a IClonable interface)

查看:45
本文介绍了如何在 Typescript 接口中引用 self 的类型(对于 IClonable 接口)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 IClonable 接口来定义一个 clone() 成员,该成员返回实现它的类的实例.

如果可能,我如何指示 clone() 的返回类型将与调用它的类相同?

interface IClonable {克隆():???}

我知道我可以用下面的泛型来做到这一点,但这似乎过于冗长

interface IClonable;{克隆():T}

解决方案

非常简单地将返回类型设置为 (polymorphic) this:

interface ICloneable {克隆():这个;}

<块引用>

多态 this 类型表示作为包含类或接口.这称为F有界多态性.


重要提示

似乎有一个 [问题][5] 实际上在一个类中使用了一个像上面那样定义的接口.问题是尝试覆盖新类中的方法不起作用.我的建议 atm 将推迟使用此语法或不在接口中使用它,而更喜欢使用类,以便您可以提供基本的实现.似乎引入它主要是为了能够正确地进行方法链接.

OP 最初似乎是目前实现此目标的最佳方法:

interface ICloneable;{克隆():T;}A类实现ICloneable{构造函数(只读一个:数字){}克隆(){返回新的 A(this.a);}}

甚至

interface ICloneable {克隆():ICloneable;}

正如另一个答案指出的那样.

I need an IClonable interface that defines a clone() member, that returns an instance of the class that implemented it.

If possible, how can I indicate that the return type of clone() will be the same as the class it is called on?

interface IClonable {
    clone(): ???
}

I know I can do this with generics like below, but that seems overly verbose

interface IClonable<T> {
    clone(): T
}

解决方案

Very simply set return type as (polymorphic) this:

interface ICloneable {
    clone(): this;
}

A polymorphic this type represents a type that is the subtype of the containing class or interface. This is called F-bounded polymorphism.


Important Note

There seems to be an [issue][5] with actually using an interface defined like the one above, in a class. The problem is that attempting to override the method in a new class does not work. My suggestion atm would be to hold off on using this syntax or not to use it in an interface and prefer to use a class so that you can provide a basic implementation. It seems that it was introduced mostly to be able to do method chaining properly.

What the OP had initially seems to be the current best way to accomplish this:

interface ICloneable<T> {
  clone(): T;
}

class A implements ICloneable<A> {
  constructor(readonly a: number){}

  clone() {
    return new A(this.a);
  }
}

or even

interface ICloneable {
  clone(): ICloneable;
}

as another answer pointed out.

这篇关于如何在 Typescript 接口中引用 self 的类型(对于 IClonable 接口)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆