Your mistake has been pointed out correctly. In the case where your class
implements an interface
, it is necessary to implement all the specified properties and methods. If there are certain properties or methods that you do not wish to implement, you can label them as optional
by adding a ?
symbol.
interface Base {
required: string;
someProperty?: string; // Notice the `?` indicating optional
}
When implementing the interface, you have the flexibility to omit the someProperty
if desired:
class MyClass implements Base{
required: string;
method(): void {
this.required="ddd";
console.log(this.required);
// Accessing HTMLElement is possible
}
}
Interfaces are not only for implementation purposes; they can also serve as types. For example, defining an interface:
interface Base {
required: string;
}
Allows you to create objects which adhere to that specific interface:
const obj: Base = { };
However, attempting to assign an object of type Base
without providing all required properties will result in an error. Therefore, complete initialization is necessary:
const obj: Base = { required: 'Yes' };
This approach enhances code robustness and provides strong typing, even for objects that don't require a dedicated class but must conform to a particular structure.
For instance:
An interface is defined as follows:
interface Name {
name: string
}
With corresponding classes:
class Car implements Name {
name: string;
engine: string
constructor(name: string, engine: string){
this.name = name;
this.engine = engine;
}
}
class Person implements Name {
name: string;
surname: string;
constructor(name: string, surname: string){
this.name = name;
this.surname = surname;
}
}
var arr: Name = [new Car('Car', 'JZ'), new Person('Name', 'Surname')];
In this scenario, arr
represents an array of type Name
. Thus, accessing arr[0]
and calling
.engine</code will result in an error because <code>Name
does not include an
engine
property. However, the existence of a
name
property is guaranteed for every object within the array due to the mandatory nature of the
name
property in the
Name
type.