0

I have this function where i am making fullName of some object


interface Person {
  firstName: string;
  lastName: string;
}

  makeFullName(obj: Person) {
    return {
      ...obj,
      fullName: `${obj.firstName} ${obj.lastName}`
    }
  }

so when i try to send object that is diffrent than the type

    let obj = this.makeFullName({ firstName: 'Williams', lastName: 'John', age: 23 });

i get expected error

Argument of type '{ firstName: string; lastName: string; age: number; }' is not assignable to parameter of type 'Person'.

because i don't have age as as type in Person.

but when i do the same in other variable

let user = { firstName: 'Williams', lastName: 'John', age: 23 }
    let obj = this.makeFullName(user);

i don't get that error. Why is that ? When i hover on user variable i still get the inferred type

 firstName: string;
    lastName: string;
    age: number;

why it is working on this way ?

  • 1
    [Excess property checks](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks) are explicitly only done when you directly use an object initialiser and not if you assign to a variable first. – VLAZ May 05 '22 at 09:29
  • 1
    Does this answer your question? [Why can I avoid excess property check in typescript just by passing a reference to an object to a function rather than the object in its literal form?](https://stackoverflow.com/questions/52852278/why-can-i-avoid-excess-property-check-in-typescript-just-by-passing-a-reference) – VLAZ May 05 '22 at 09:30

0 Answers0