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 } =
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
}];
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
}];
In one of our strictest repos at work we declare explicit types on array containers, which would look like this, if you're interested in seeing it organised professionally:
interface CarType {
type: string
model: string
year: number
}
type CarsType = CarType[]
const list_of_cars: CarsType = [
{ type: 'Toyota', model: 'Corolla', year: 2009 },
{ type: 'Ford', model: 'Mustang', year: 1969 },
]