PandaWood
PandaWood

Reputation: 8363

TypeScript object cast to interface should not compile?

I can't understand why this TypeScript code should compile (TypeScript 2.8.3 all strict checks on)

I've cast an object to type IUser and included a property which doesn't exist "bob"

I've read the documentation on excess checks - https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks

But it still doesn't make sense that this should compile - given I'm casting it.

The ultimate question is: How can I actually get proper typing on this object - such that casting it to an object with non-interface members (a possibly/likely typo) should fail to compile.

interface IUser {
    name: string
}

const func = (user: IUser) => {
    alert(user)
}

func(<IUser> {
    name: "bob",
    bob: true
} as IUser)

Upvotes: 1

Views: 474

Answers (1)

artem
artem

Reputation: 51679

Extra properties check is done only when assigning object literal to a variable or function parameter. Adding any kind of cast disables the check, because the value actually is assignable to the type. This feature is called Strict object literal assignment checking:

It is an error to specify properties in an object literal that were not specified on the target type, when assigned to a variable or passed for a parameter of a non-empty target type.

Example where the an extra property gives an error:

interface IUser {
  name: string
}

const anotherFunc = function (u: IUser) {
    // whatever
}

const func = function() {
    anotherFunc({
        name: "bob",
        bob: true
    })
}

// Argument of type '{ name: string; bob: boolean; }' is not assignable to parameter of type 'IUser'.
//   Object literal may only specify known properties, and 'bob' does not exist in type 'IUser'.

Upvotes: 3

Related Questions