Joji
Joji

Reputation: 5646

TypeScript: Why is the same object cannot be assigned with the interface when defined but can be assigned when passed as a parameter

Here I have a object and an interface, its shape is like this

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

const obj: OBJ = { firstName: "John", lastName: "Smith", random: 1 };

Here clearly TS compiler would error on 'random' does not exist in type 'OBJ'.

However if I have a function as this

const getNewObj = (obj: OBJ) => ({
  fullName: obj.firstName + obj.lastName,
  ...obj
});

then I pass obj into this function console.log(getNewObj(obj));

There is no error. How come?

Live demo: https://codesandbox.io/s/eager-joliot-s4j93?file=/src/index.ts:289-318

Upvotes: 3

Views: 522

Answers (1)

akram-adel
akram-adel

Reputation: 1070

TypeScript has this Strict object literal checking. simply put for functions: if you pass an object reference (variable or constant) to the function, typescript will check if this object reference contains the keys required for your function. Nothing less, but will allow from more keys.
Example of this:

const getNewObj = (obj: OBJ) => ({
  fullName: obj.firstName + obj.lastName,
  ...obj
});

const obj1 = {firstName: "John", lastName: "Smith", random: 1}
const obj2 = {lastName: "Smith", random: 1}

getNewObj(obj1); // This is good, eventhough property random is extra
getNewObj(obj2); // Error: property firstName is missing

On the other hand, if you pass your function an object (not an object reference), then typescript will type check that object and throws an error for missing and extra properties
Example, with the same function:

getNewObj({ firstName: "John", lastName: "Smith" }) // good
getNewObj({ firstName: "John", lastName: "Smith", random: 1 }) //'random' does not exist..
getNewObj({ lastName: "Smith" }) // Property 'firstName' is missing...

More detail on this Strict object literal can be found in this gitbook

Upvotes: 4

Related Questions