TypeScript. Interfaces

Home » Tutorials » JavaScript » TypeScript. Interfaces
In this lesson we’ll talk about interfaces in TypeScript.
As we know, JavaScript has got several build-in types. But in our programs we often use objects with different structure and nesting. For typing these interfaces interfaces are used.
Interfaces description can contain properties and methods.
In fact interface make you realize all its props and methods. But you can define interface property or method as optional using question mark sign.

Code lesson

interface Product {
	id: number;
	name: string;
	category: Category;
	getCategoryId: (categoryId: number) => void
}

interface Category {
	id: number;
	name: string;
}

interface ProductType {
	[id: number]: string;
}


interface Figure {
	name: string;
}

interface Triangle extends Figure {
	corners: number;
}

let product: Product = {
	id: 1,
	name: 'iphone',
	category: {
		id: 1,
		name: 'smartphones'
	},
	getCategoryId: (categoryId) => {
		console.log(++categoryId)
	}
}

console.log(product);
product.getCategoryId(2);

let types: ProductType = ['STOCK', 'SOLVED'];
console.log(types)
console.log(types[0]);


let triangle: Triangle = {
	name: 'triangle',
	corners: 1
};

console.log(triangle);

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This