TypeScript Interfaces Type
Last Updated :
16 May, 2024
Improve
TypeScript Interfaces Type offers an alternative method for defining an object's type, allowing for a distinct naming approach.
Syntax:
interface InterfaceName {
property1: type1;
property2?: type2;
readonly property3: type3;
// ...
method1(): returnType1;
method2(): returnType2;
// ...
}
Parameters:
- interface is the keyword itself which is used to declare the intreface.
- InterfaceName is the name of the interface.
- property1 is the name of the property in an interface.
- type1 is the type of the property1 in the interface.
- method()1 is the method name of the method in the interface.
- returnType1 is the type of return value of the method()1.
Example 1: In this example, one Employee
object is defined, and its properties are displayed with in the console output.
interface Employee {
// The readonly-indicates id cannot be modified
readonly id: number;
firstName: string;
lastName: string;
age: number;
//The ?-indicates city is a optional property
city?: string
}
// Create an object adhering
// to the Employee interface
const employee1: Employee = {
id: 1,
firstName: "John",
lastName: "Doe",
age: 30,
};
console.log(`Employee:First Name : ${employee1.firstName}
,Last Name : ${employee1.lastName},Age : ${employee1.age}`);
Output:
"Employee:First Name : John,Last Name : Doe,Age : 30"
Example 2: In this example, a Circle
class is implemented, adhering to the Shape
interface, and an instance of the circle is created and its color and area are displayed in the console.
interface Shape {
color: string;
area(): number;
}
interface Circle extends Shape {
radius: number;
}
class CircleImpl implements Circle {
constructor(public color: string,
public radius: number) { }
area(): number {
return Math.PI * this.radius ** 2;
}
}
const myCircle = new CircleImpl("red", 5);
console.log(`Color: ${myCircle.color},
Area: ${myCircle.area()}`);
Output:
"Color: red,
Area: 78.53981633974483"
Example 3: In this example, a hybrid interface type for a Product object is defined, and a runtime validation method is added to check object conformity.
interface HybridProduct {
readonly id: number;
name: string;
price: number;
description?: string;
validate(obj: any): boolean;
}
const HybridProduct: HybridProduct = {
id: 0,
name: '',
price: 0,
validate(obj: any): boolean {
if (typeof obj.id !== 'number' || typeof obj.name !== 'string' || typeof obj.price !== 'number') {
return false;
}
if (obj.description && typeof obj.description !== 'string') {
return false;
}
return true;
}
};
const product = {
id: 1,
name: "Laptop",
price: 1500
};
console.log(`Product is valid: ${HybridProduct.validate(product)}`);
Output:
"Product is valid: true"