Home > OS >  How to write this list in Typescript? it is currently in Javascript, It is list of cars,
How to write this list in Typescript? it is currently in Javascript, It is list of cars,

Time:05-28

How to write this list in Typescript? I know the code works in TypeScript, but I want the list to have declarative types. it is currently in Javascript, it is list of cars :

const list_of_cars = [{
  type: "Toyota",
  model: "Corolla",
  year: 2009
},
  type: "Ford",
  model: "Mustang",
  year: 1969
}];

I know have tried const car: { type: string, model: string, year: number } =

CodePudding user response:

Typically, you can define a type or interface for specific objects and specify the individual types for each attribute. You can then define your list as an array of the specific interface or type you defined.

Example:

interface Car {
 type: string
 model: string
 year: number
}

const listOfCars: Car[] = [{
  type: "Toyota",
  model: "Corolla",
  year: 2009
},
  type: "Ford",
  model: "Mustang",
  year: 1969
}];

CodePudding user response:

This is also a valid in typescript. If you want in types then you can write it like this

const list_of_cars:{type:string, model:string,year:number}[] = [{
  type: "Toyota",
  model: "Corolla",
  year: 2009
},{
  type: "Ford",
  model: "Mustang",
  year: 1969
}];

OR you can declare an type and use that

type car={type:string, model:string,year:number}
const list_of_cars : car[] = [{
  type: "Toyota",
  model: "Corolla",
  year: 2009
},{
  type: "Ford",
  model: "Mustang",
  year: 1969
}];
  • Related