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 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.
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