🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
An Interface is a structure that acts as a contract in our application. It defines the syntax for classes to follow, which means a class that implements an interface is bound to implement all its members. We cannot instantiate the interface, but it can be referenced by the class object that implements it.
Learn typescript at TypeScript Tutorial with Examples.
The TypeScript compiler does not convert the interface to JavaScript. It uses interface for type checking. This is also known as "duck typing" or "structural subtyping".
Table of Contents
- Simple Interface Example
- Interface Optional Properties Example
- Interface Readonly properties Example
- Extending Interfaces Example
- Implementing an Interface Example
- Interface for Array Type Example
1. Simple Interface Example
export interface Employee{
firstName: string;
lastName: string;
fullName(): string;
}
let employee: Employee = {
firstName : "ramesh",
lastName: "fadatare",
fullName(): string{
return this.firstName + " " + this.lastName;
}
}
console.log(employee.firstName);
console.log(employee.lastName);
console.log(employee.fullName());
Output:
C:\typescript-tutorial> tsc interfaces.ts
C:\typescript-tutorial> node interfaces.js
ramesh
fadatare
ramesh fadatare
The above typescript code is compiled into below plain JavaScript code:
"use strict";
exports.__esModule = true;
var employee = {
firstName: "ramesh",
lastName: "fadatare",
fullName: function () {
return this.firstName + " " + this.lastName;
}
};
console.log(employee.firstName);
console.log(employee.lastName);
console.log(employee.fullName());
Note that the TypeScript compiler does not convert the interface to JavaScript.
2. Interface Optional Properties Example
Not all properties of an interface may be required. Interfaces with optional properties are written similar to other interfaces, with each optional property denoted by a ? at the end of the property name in the declaration.
Here’s an example of this pattern:
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): {color: string; area: number} {
let newSquare = {color: "white", area: 100};
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color: "black"});
console.log(mySquare);
Output:
{ color: 'black', area: 100 }
The advantage of optional properties is that you can describe these possibly available properties while still also preventing the use of properties that are not part of the interface.
3. Interface Readonly properties Example
TypeScript provides a way to mark a property as readonly. This means that once a property is assigned a value, it cannot be changed!:
interface Point {
readonly x: number;
readonly y: number;
}
You can construct a Point by assigning an object literal. After the assignment, x and y can’t be changed.
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!
4. Extending Interfaces Example
Interfaces can extend one or more interfaces. This makes writing interfaces flexible and reusable.
interface IAddress {
address: string;
}
interface IPerson extends IAddress{
firstName: string;
lastName: string;
}
interface IEmployee extends IPerson {
employeeCode: number;
}
let employeeObj: IEmployee = {
firstName: "ramesh",
lastName: "fadatare",
address: "pune",
employeeCode: 100
}
console.log(employeeObj);
Output:
{ color: 'black', area: 100 }
{ firstName: 'ramesh',
lastName: 'fadatare',
address: 'pune',
employeeCode: 100 }
5. Implementing an Interface Example
Similar to languages like Java and C#, interfaces in TypeScript can be implemented with a Class.
interface Employee {
name: string;
paymentPerHour: number;
workingHours: number;
calculateSalary(): number;
}
class Contractor implements Employee {
name: string;
paymentPerHour: number;
workingHours: number;
constructor(name: string, paymentPerHour: number, workingHours: number) {
this.name = name;
this.paymentPerHour = paymentPerHour;
this.workingHours = workingHours;
}
calculateSalary(): number {
return this.paymentPerHour * this.workingHours;
}
}
class FullTimeEmployee implements Employee {
name: string;
paymentPerHour: number;
workingHours: number;
constructor(name: string, paymentPerHour: number) {
this.name = name;
this.paymentPerHour = paymentPerHour;
}
calculateSalary(): number {
return this.paymentPerHour * 8;
}
}
let contractor: Employee;
let fullTimeEmployee: Employee;
contractor = new Contractor('Ramesh contractor', 10, 5);
fullTimeEmployee = new FullTimeEmployee('Ramesh full time employee', 8);
console.log(contractor.calculateSalary());
console.log(fullTimeEmployee.calculateSalary());
Output:
C:\typescript-tutorial> tsc interfaces.ts
C:\typescript-tutorial> node interfaces.js
50
64
6. Interface for Array Type Example
An interface can also define the type of an array where you can define the type of index as well as values
interface NumList {
[index:number]:number
}
let numArr: NumList = [1, 2, 3];
numArr[0];
numArr[1];
console.log(numArr);
// Array which return string
interface ProLangArray {
[index:number]:string
}
// use of the interface
let progLangArray : ProLangArray = ['C', 'C++', 'Java', 'Python'];
console.log(progLangArray);
Output:
[ 1, 2, 3 ]
[ 'C', 'C++', 'Java', 'Python' ]
Learn typescript at TypeScript Tutorial with Examples.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
🆕 High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
🆕 High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
🚀 Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
🌟 Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
🌟 Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
🎓 Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Comments
Post a Comment
Leave Comment