Typescript doesn't throw `state` errors outside of constructor?

enter image description here

In the image above, I have incorrectly set the defaults state

( this_is_not_ok

not part of the interface state

). Typescript doesn't seem to mind. One way to fix the problem is to explicitly add the type annotation.

I could also fix the problem using constructor()

:

constructor(){ super(); this.state = {spelling_error: "wrong"}; }

Why didn't type inference work in the first example?

+3


source to share


1 answer


I set the default status values ​​incorrectly

You did not enter the values ​​correctly. You just wrote a class that has more state than the base class, which is not a bug per se. When you write a derived class, you can have more stuff than your base class.

When you write a class property initializer without a type annotation, TypeScript specifies the type of the property based on the initializer:

interface Bar {
  stuff: { x: number }
}

class Foo implements Bar {
  stuff = {
    x: 10, y: 3
  }
}
const f = new Foo();
console.log(f.stuff.y); // OK: f.stuff is of type { x: number; y: number; }

      



Validation implements

simply means "Make sure this class can be used as an interface type." The same goes for the derived class: because you have at least the material specified by the base class contract, then everything is fine.

If you have an explicit type annotation or initialization in a constructor, then the general rules for assigning an object literal apply - no additional properties are allowed.


For what it's worth, this behavior may change in a future version of TypeScript. See https://github.com/Microsoft/TypeScript/issues/10570

+8


source







All Articles