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',
});
PeterFox
  • 43
  • 2
  • The error in the latter case is [excess property checking](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-6.html#stricter-object-literal-assignment-checks) 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. – jcalz Jun 19 '23 at 15:46

0 Answers0