0% found this document useful (0 votes)
2 views3 pages

Simulating Interfaces in JavaScript

Uploaded by

chennujaswanth7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Simulating Interfaces in JavaScript

Uploaded by

chennujaswanth7
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Interface in JavaScript

========================

JavaScript does NOT have a built-in interface keyword like Java or TypeScript.
But you can simulate interfaces in JavaScript to enforce certain structure in your objects.

1. What is an Interface?
-------------------------
An interface is basically a 'contract' that says:
'Any class or object implementing this must have these properties/methods.'

In JavaScript, there is no direct language feature for interfaces - this concept comes from
TypeScript.
In plain JS, interfaces are simulated using classes, objects, or comments.

2. Simulating Interface in JavaScript


---------------------------------------

Option 1 - Using a Class as Interface


---------------------------------------
class AnimalInterface {
speak() {
throw new Error("Method 'speak()' must be implemented.");
}
}

class Dog extends AnimalInterface {


speak() {
[Link]("Bark!");
}
}
let dog = new Dog();
[Link](); // Bark!

Here, AnimalInterface acts like an interface by forcing Dog to have a speak() method.

Option 2 - Using Comments & Conventions


-----------------------------------------
// Interface: Vehicle
// - start()
// - stop()

class Car {
start() {
[Link]("Car started.");
}
stop() {
[Link]("Car stopped.");
}
}

Option 3 - Using TypeScript for True Interfaces


If you really want interfaces, you need TypeScript, which extends JavaScript.
------------------------------------------------
interface Animal {
speak(): void;
}

class Dog implements Animal {


speak() {
[Link]("Bark!");
}
}

Here TypeScript enforces the interface at compile time.


Summary
-------
- JavaScript -> no native interface keyword.
- You simulate interfaces using abstract classes, object patterns, or conventions.
- For strict interface enforcement -> use TypeScript.

You might also like