Open In App

TypeScript Interfaces Type

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:

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"

Article Tags :