TypeScript Interfaces Type
Last Updated :
09 Nov, 2023
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.
Javascript
interface Employee {
readonly id: number;
firstName: string;
lastName: string;
age: number;
city?: string
}
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.
Javascript
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"
Share your thoughts in the comments
Please Login to comment...