Why does TypeScript not complain about properties not included in the state when casting?

Viewed 166

Why does TypeScript behave the way it does in my case?

If I directly type an object, it complains about properties which are not defined in the interface. But if I cast the object it allows do add any random properties not defined in the interface.

Best explained with an example:

interface House {
  windows: number;
  garden: boolean;
}

const house1: House = {
  windows: 5,
  garden: true,
  garage: true // not allowed
};

const whatever = {
  house2: <House> {
    windows: 3,
    garden: true,
    garage: true // why is it here allowed?
  }
};
1 Answers

It works because it is a Type Assertion. Basically telling the compiler what type it is but not guarding it e.g.

const house1 = <House> {
  windows: 5,
  garden: true,
  garage: true // allowed
};

Basically you tell the ts-compiler to not perform special checking or restructuring of data.

You would type guard it with the appropriate type for the properties e.g.

const whatever: { house2: House } = {
    house2: {
        windows: 3,
        garden: true,
        garage: true // not allowed
    }
};
Related