1

Why does the save-call with myUser variable work but the call with inline value not work? Typescript playground

interface User {
    username: string;
}

function save(user: Partial<User>) {

}

const myUser = {
    username: 'John',
    foo: 'bar',
} as const;
// no error
this.save(myUser);

// error: Argument of type '{ username: string; foo: string; }' is not assignable to parameter of type 'Partial<User>'.
// Object literal may only specify known properties, and 'foo' does not exist in type 'Partial<User>'
this.save({
    username: 'John',
    foo: 'bar',
});
1
  • The error in the latter case is excess property checking which only happens in some circumstances where the compiler thinks you might be making a mistake by specifying a property whose existence will be completely forgotten. In the case of this.save(myUser), myUser exists and all its properties are accessible. In this.save{username: "John", foo: "bar"}, the foo property will likely be forgotten. See the linked questions/answers for more info. Commented Jun 19, 2023 at 15:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.