I'm generating TypeScript classes that use Inheritance. Each of the Classes uses a static create-function, which may be different.
class A {
static create(arg: string): A {
// use args to create A
return new A()
};
}
class B extends A {
static create(argsForB: number): B {
// use argsForB to create B
return new B()
};
}
Since static functions should not be inherited anyway, this Error does not make any sense:
Class static side 'typeof B' incorrectly extends base class static side 'typeof A'.
Types of property 'create' are incompatible.
Type '(argsForB: number) => B' is not assignable to type '(arg: string) => A'.
Types of parameters 'argsForB' and 'arg' are incompatible.
Type 'string' is not assignable to type 'number'.
I know one solution would be to simply rename the create-funtion to createA and createB, but it does not feel right.
Remember that Typescript is mainly a superset of recent ECMAscript rules. Generally speaking, Javascript does not have types, thus Typescript is preventing you from creating a class for which it thinks Javascript will be unable to discern which version you mean to call. It cannot enforce execution of one version or the other because the generated code is the same for both, from the TS perspective. Also note that this has nothing to do with the methods being static. If you remove the static qualifier you will get an error on the create method of the second class with a similar message.
Take a look at the generated typescript on the Playground and you see what it means: Typescript Playground example
I still don't quite understand what you aim to do in this instance, but doing something like this will remove the issue, albeit probably not solve what you are trying to get done:
class A {
static create(arg: string | number): A {
// use args to create A
return new A()
};
}
class B extends A {
static create(argsForB: string | number): B {
// use argsForB to create B
return new B()
};
}
There are many constructs that work fine in Javascript, that Typescript calls out as errors because the way they work does not allow for enforcement of the type rules.
Consider the following:
class A {
content: string;
static create(arg: string): A {
// use args to create A
let result = new A();
result.content = arg;
return new A()
};
}
class B extends A {
content: number;
static create(argsForB: number): B {
// use argsForB to create B
let result = new B();
result.content = argsForB;
return result;
};
sendMessage
}
let testB = B.create(5);
alert(testB.content);
let testCastA = testB as A;
alert(testCastA.content);
As before, Javascript is generated that makes this work, but it does not do what I would expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With