How to reference type of self in Typescript interf

2020-08-26 03:47发布

问题:

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
}

回答1:

Very simply set return type as (polymorphic) this:

interface IClonable {
    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.



回答2:

You are right, using generics is the way to do it, even if it's verbose..

You can also:

interface IClonable {
    clone(): any;
}

or

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

or

interface IClonable {
    clone(): IClonable;
}

But using generics is probably the best way to go.


Edit

@Silvermind comments below made me check the suggested code of clone<T>(): T and I was wrong as it does not compile.
First Here's a code to show what I meant:

class Point implements IClonable {
    private x: number;
    private y: number;
    
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
    
    public clone<T>(): T {
        return <T> new Point(this.x, this.y);
    }
}

var p1 = new Point(1, 2);
var p3 = p1.clone<Point>();

Basically to perform the cast in the clone method instead of casting the returned value.
But <T> new Point(this.x, this.y) produces:

Neither type 'Point` nor type 'T' is assignable to each other



标签: typescript