Reputation: 2371
I was following this example from the Typescript documentation:
class Sprite {
name = "";
x = 0;
y = 0;
constructor(name: string) {
this.name = name;
}
}
type GConstructor<T = {}> = new (...args: any[]) => T;
type Spritable = GConstructor<typeof Sprite>;
Next, implemented a function that generates a class extending this type like this:
function Example<TBase extends Spritable>(Base: TBase) {
return class Example extends Base {
hello() {
console.log("hello");
}
};
}
I assumed that I would then utilise this Mixin like this:
const x = Example(Sprite);
However, this throws the error
Argument of type 'typeof Sprite' is not assignable to parameter of type 'Spritable'.
If I modify the param passed into the generic constructor to be type Spritable = GConstructor<Sprite>;
, the above code works.
However, in the typescript docs it's implemented using typeof
which throws me an error. What am I doing wrong here?
Upvotes: 2
Views: 175
Reputation: 15106
This appears to be a mistake in the documentation. The generic parameter T
is the return type of the constructor, so it should be the object type Sprite
rather than the class type typeof Sprite
.
I've submitted a PR to fix it: https://github.com/microsoft/TypeScript-Website/pull/1862
Update: The PR has been merged and the Constrained-mixins documentation now uses GConstructor<Sprite>
istead of GConstructor<typeof Sprite>
.
Upvotes: 4