2

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

1 Answer 1

3

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
    }
};
Sign up to request clarification or add additional context in comments.

9 Comments

Could you please make the distinction between "type casting" and "type assertions" more clear?
@k0pernikus There is no "type casting", there is not much difference between both terms. Typescript called it "type assertion" since it sounds more like the language framework. Other than that, "casting" implies that there might be a run time support in other languages, but in Typescript it is purely at compile time.
Ok, and is there a way to cast it, that it’s not only telling the compiler what type it is, but also guards it?
@mnewmedia Added.
Ok, got it. But since in real-life app the house2 is wrapped by an object(whatever) which is in an array. And sometimes it’s a different type than a House. So the way it behaves makes it now, much more complicated than it could be.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.