Web Technologies - TypeScript

Back to Course

Lesson Description

Lession - #1446 TypeScript Object Types

TypeScript has a specific syntax for typing objects.


 const car: { type: string, model: string, year: number } = {
  type: "Toyota",
  model: "Corolla",
  year: 2009

Type Inference
TypeScript can infer the types of properties based on their values.


 const car = { 
 type" Toyota", 
 = " Ford";// no error 
 = 2;// Error Type' number' isn't assignable to type' string'. 

Optional Properties
Optional properties are properties that do not have to be defined in the object definition.

illustration without an optional property

 const car{ type string, mileage number} = {// Error Property' mileage' is missing in type'{ type string;}' but required in type'{ type string; mileage number;}'. 
 type" Toyota", 
 = 2000; 

illustration with an optional property

const car{ type string, mileage? number} = {// no error 
 type" Toyota" 
 = 2000; 

Index Signatures
Index signatures can be used for objects without a defined list of properties.


 const nameAgeMap{( indicator string>
number} = {}; = 25;// no error = " Fifty";// Error Type' string' isn't assignable to type' number'.

Online compiler