Controlling Object Structure in TypeScript
TypeScript also controls the structure of the object. Let's say we declared our object with a user:
let user = {name: 'john', age: 30};
At declaration time, TypeScript remembers that our object has keys 'name' and 'age', and then makes sure that the variable stores an object with exactly these keys.
Trying to write another object to a variable results in a compilation error. Let's try. Let's write an object to a variable that lacks a key:
user = {name: 'eric'}; //
Let's write a new object into a variable with the same keys, but also with an extra key:
user = {name: 'eric', age: 40, salary: 300}; //
Now let's write into a variable an object containing only the keys 'name' and 'age':
user = {name: 'eric', age: 40}; // works
Without running the code, determine what the result of executing the code will be:
let date = {year: 2025, month: 12, day: 31};
date = {year: 2025, month: 12};
Without running the code, determine what the result of executing the code will be:
let date = {year: 2025, month: 12, day: 31};
date = {year: 2025, month: 12, date: 7};