I don't understand why the error 2322 is occurring.
Please examine the following code snippet:
interface Fish {
alive: string | boolean;
}
class FishClass implements Fish {
alive = 'Yes'
constructor() {
// Type 'boolean' is not assignable to type 'string'.(2322)
this.alive = true;
}
}
The interface defines the union type for string | boolean.
Why is the type fixed when I assigned one of the two possible types to the field inside the class that implements the interface?
CodePudding user response:
Despite most people's expectations, class members are not contextually typed by the types they are declared to implement or extend. An extends
or implements
declaration on a class has no effect whatsoever on the type of the class instance. Instead, it just does a check of the class against the superclass or interface after the fact. So if your class fails to implement or extend what you've declared it to, you'll get a compiler warning. But when it comes to the resulting types, it will be the same as if you removed the extends
or implements
clause entirely. No, nobody likes this.
See microsoft/TypeScript#3667 for the original request to fix this, and there was an attempt at microsoft/TypeScript#6118 but it was eventually abandoned due to some problems with existing libraries; see this comment. There are several open issues about this, including microsoft/TypeScript#32082; if you want to see this addressed you might want to go to that issue and give it a