Issue
Can some one explain how to create our own custom types in angular using typescript syntax. Please provide example as well. Thanks!
Solution
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;
}
Answered By - DeborahK
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.