Interfejsy dla klas OOP w TypeScript
Interfejsy w TypeScript są szeroko stosowane
również jako szablony dla klas. Aby zastosować
do klasy wymagany interfejs,
po nazwie klasy pisze się słowo kluczowe
implements a następnie nazwę interfejsu.
Przy tym interfejsy opisują tylko właściwości i metody publiczne klasy. Część prywatna jest definiowana w samej klasie i nie jest opisana w interfejsie.
Wypróbujmy w praktyce. Załóżmy, że mamy następujący interfejs, definiujący właściwość i metodę:
interface IUser {
name: string;
greet(): string;
}
Stwórzmy klasę implementującą ten interfejs.
W tej klasie muszą być zaimplementowane
właściwość name i metoda greet:
class User implements IUser {
name: string;
constructor(name: string) {
this.name = name;
}
greet() {
return `hello, ${this.name}!`;
}
}
Utwórz interfejs IMath z właściwościami
num1 i num2 oraz metodą
getDiv, która będzie dzielić pierwszą
liczbę przez drugą.
Stwórz klasę Math, która implementuje
interfejs IMath.