Object structure in TypeScript
You can choose not to rely on TypeScript to determine the structure of an object, but specify it as a type when declaring a variable.
For example, when declaring a variable user
, let's say that it is an object, in the field 'name'
of which a string is stored, and in the field 'age'
- a number:
let user: {name: string, age: number};
Let's now write the corresponding object into our variable:
user = {name: 'john', age: 30};
You can merge both operations into one line: declare an object and immediately write a value to it:
let user: {name: string, age: number} = {name: 'john', age: 30};
After that, TypeScript will take care of the structure and data types of the object and will throw an error if you try to change something incorrectly. Example:
user.name = 123; //
Without running the code, determine what the result of executing the code will be:
let date: {year: number, month: number, day: number};
date = {year: 2025, month: 12, day: '01'};