Defining Interfaces

One of the benefit of using TypeScript is its strong typing.



Strong typing means, every property has a data type, every method has a data type, every method's parameter has a data type and so on.

A strong type helps minimising the errors through better syntax checking. In some cases, we do not have strong typing. 'products: any[]' array for example. To define custom data type, we use interfaces.

Note: ES5 and ES6/ES2015 do not support interface but typscript supports interface.



Example of interface
export interface IProduct {
  productId: number;
  productName: string;
  productCode: string;
  releaseDate: string;
  price: number;
  description: string;
  starRating: number;
  imageUrl: string;
}

where,
'export' is a export keyword
'interface' is interface keyword
'IProduct' is Interface name with the prefix 'I'

Now, lets use interface in our application. In 'products' folder create a new file name 'product.ts' add the following code:
export interface IProduct {
  productId: number;
  productName: string;
  productCode: string;
  releaseDate: string;
  price: number;
  description: string;
  starRating: number;
  imageUrl: string;
}

Then in 'product-list.component.ts', import Interface at the top and replace 'any[]' with 'IProduct[]'.

Share this

Related Posts