I have a base class with the following structure:
class Base {
protected constructor() {}
static create() {
return new this;
}
}
However, when I extend this class and attempt to initialize it, a TypeScript error occurs.
class Bar extends Base {
magic() {}
}
let bar: Bar;
bar = Bar.create(); // <-- Typescript error
The error message states:
Property 'magic' is missing in type 'Base' but required in type 'Bar'
It appears that TypeScript assumes the returned value of create
is an instance of Base
, rather than Bar
.
To resolve this issue, we can make the necessary adjustments as shown below:
class Base {
protected constructor() {}
static create<T>(): T {
return new this as T;
}
}
And then assign the correct type like so:
bar = Bar.create<Bar>();
It may seem unnecessary to explicitly specify the return type since it should be clear, but how can we inform TypeScript about the exact return type?