FewV minutes of Object types in Typescript.

» Object in TypeScript

  1. TypeScript has a specific syntax for typing objects.
  2. To define an object type, we have to simply write its properties and their types. Let’s say for example:
let person: { name: string; age: number; id: number } = {
  name: "John",
  age: 34,
  id: 1,
};

console.log("Person name is " + person.name);
console.log("Person age is " + person.age);
console.log("Person id is " + person.id);

Console:

Person name is John
Person age is 34
Person id is 1
  1. In above example. Person is an object which has a name, age, and id as its properties that have a type of string, number, and number respectively.

» Object Type Inference

  1. We can even declare an object without mentioning its type for each value, typescript will infer the type of the properties based on the value typed. Let’s see with an example:
// Objects Type Inference
let person2 = {
  name: "Bob",
  age: 21,
};

console.log("Person2 name is " + person.name);
console.log("Person2 age is " + person.age);

Console:

Person2 name is Bob
Person age is 21
  1. In the above example, TypeScript infers the type of name to be a string and age to be a type number.

  2. Now when we try to re-assign its properties type like this:

person2.name = "Mary"; //no error
person2.age = "21"; //error: Type 'string' is not assignable to type 'number'.
console.log("Person2 name is " + person2.name);

Console:

Person2 name is Mary

» Optional properties in an object

  1. Optional properties mean property in an object is optional. It can be in the object or it cannot be.
// Without Optional properties
let person3: { name: string; age: number } = {
  name: "Jane",
};
console.log("Person3 name is " + person3.age);
// error: Property 'age' is missing in type '{ name: string; }'
//but required in type '{ name: string; age: number; }'.

Console:

Person3 age is undefined
  1. Here, not declaring person3 age will throw an error because the person3 object has already declared that in person3 there are going to be two properties one, name, and second, age, so when age is not declared in object person3 TypeScript will throw an error.
// With Optional properties
let person3: { name: string; age?: number } = {
  name: "Jane",
};
person3.age = 21; // no error because age is optional.

console.log("Person3 age is " + person3.age);

Console:

Person3 age is 21
  1. Here there will be no error because age is optional, and it’s done by including a question mark (?) sign after the age property, which says that age is optional.

Thank You, I hope this clears Object and its Optional Properties in TypeScript.