In Typescript, the implements
keyword plays a key role in ensuring structural subtyping is maintained.
When a class
implements an interface
, instances of that class
can be treated as instances of the interface
, allowing for seamless structural subtyping.
However, there may be confusion about how a class "can be treated as the interface type" while still retaining its original type and methods as stated: "It doesn’t change the type of the class or its methods at all."
Unlike traditional inheritance where subclasses become subtypes of the parent class and inherit its methods, implementing an interface simply guarantees that an instance of the class can be used as an instance of the interface if it fully adheres to the specified contract through complete implementation.
This distinction becomes more apparent when we look at code examples and see how TypeScript handles method signatures within implemented interfaces.
The provided example with the code snippet check(s) { ... }
might appear incomplete in terms of types but satisfies the necessary contract requirements nonetheless.
To elaborate further on this scenario:
Let's consider the following interface
:
interface Checkable {
check(<b>S: Type</b>): boolean;
}
Two classes, NameChecker
and AgeChecker
, implement this interface
with distinct method signatures:
class NameChecker implements Checkable {
check(<b>name: string</b>): boolean
{
return name.toLowerCase() === "john doe";
}
}
class AgeChecker implements Checkable {
check(<b>age: number</b>): boolean
{
return age === 50;
}
}
Despite the differences in method signatures, the above implementations are deemed valid by the implements
keyword due to the principles of structural typing upheld by TypeScript. This allows for flexibility in function declarations as long as they satisfy the contract outlined in the corresponding interface.
[1] While Typescript already leverages structural subtyping, the inclusion of the implements
keyword enforces strict adherence to the specified contract, hence the emphasis on "ensures" in the explanation.
[2] It is essential to note that the omission of specific types leads to implicit typing as any
.