It depends on what you mean by type
exactly.
If you want to define a “type” that you can use in TypeScript strong typing, then you have several choices.
You can build an interface like this:
export interface Product {
productId: number;
productName: string;
productCode: string;
releaseDate: string;
price: number;
description: string;
starRating: number;
imageUrl: string;
}
And use it as a type like this:
const products: Product[] = [];
Or as mentioned in the comments, you can build a TypeScript class:
export class Product {
productId: number;
productName: string;
productCode: string;
releaseDate: string;
price: number;
description: string;
starRating: number;
imageUrl: string;
}
And use it similarly. With a class, you can “new” up instances, which you can’t do with an interface.
EDIT 12/28/21:
Angular by default now has strict typing on by default. This means that there is a bit more work to do when declaring a class with a set of properties. Each property must be changed using one of these techniques:
- Add
| undefined
to the type - Add a default value such as
= ''
- Use the definite assignment assertion operator (
!
), which denotes that you will take care to definitely assign it sometime later. - Make the property optional using the
?
Here is an example that uses each of the above:
export class Product {
productId: number | undefined;
productName="";
productCode!: string;
releaseDate?: string;
price?: number;
description?: string;
starRating?: number;
imageUrl?: string;
}
1
solved How to create custom type in angular [closed]