Creating Custom Typescript Types
In TypeScript you can build your own custom object types. Custom types work just like any other type. You can use it like this:
type Vehicle = {
make: string,
model: string,
capacity: number,
}
//now we can use the vehicle type in a definition
const corolla: Vehicle = {
make: "Toyota",
model: "Corolla",
capacity: 5,
}
If you define a vehicle without any of the required types, TypeScript will provide an error stating which property is missing from the object. For example:
const corolla: Vehicle = {
make: "Subaru",
model: "Outback",
}
This definition will provide an error Property 'capacity' is missing in type '{ make: string; model: string; }' but required in type 'Vehicle'.
, because the capacity property is missing.