Miguel Leon
Miguel Leon

Reputation: 200

Why are some parts of typescript type analysis inconsistent?

interface X {
    a: number;
}

const x: X = {
    a: 9,
    // somethingElse: 8 // This would result in compilation error as expected
};

const y = {
    a: 9,
    somethingElse: 8
};

const xx: X = y; // but this works

However, I would expect the same behavior as the first assignment, resulting in compilation error because of the extra property.

Upvotes: 1

Views: 220

Answers (1)

Pac0
Pac0

Reputation: 23174

The rationale I understand is this way :

Strong restriction when assigning object litteral

When defining directly your x: X, the additional property somethingElse should never be accessed, that seem to be the intent when typing this as X.

All along in the rest of the code x will always be of type X and it does not expose somethingElse, so, for the compiler, here it's the code (or the developer ;) ) that is inconsistent.

Less restriction when assigning from other variable

When you assign the other varriable xx with y, y was not explicitly typed, and thus the property somethingElse could still be used in other places.

For the compiler, you seem to temporarily restrict y to the part that matches the interface X, and that's nice. In a more complicated example maybe many different objects could fit this role, so the specific interface typing for xx is perfectly legitimate.

Upvotes: 1

Related Questions