tezvyn:

What is the purpose of the implements keyword?

AI-drafted, machine-checkedSource: typescriptlang.orgintermediate

Tests compile-time contract enforcement in TypeScript. Explain that implements checks class-to-interface compatibility at compile time with no runtime overhead, then code a CacheService with get and set methods.

WHAT THIS TESTS: Whether you understand that implements is a compile-time-only construct in TypeScript for enforcing class-to-interface contracts. It checks if you know the difference between nominal class inheritance via extends and structural type conformance via implements, and whether you can write a class that satisfies a given interface with correct method signatures and return types.

A GOOD ANSWER COVERS: First, state that implements tells the TypeScript compiler to verify that the class contains all properties and methods declared in the interface with compatible types, and that this check happens entirely at compile time with zero runtime overhead because interfaces are erased during transpilation. Second, write a CacheService class that implements ICache, including a get method that takes a string key and returns any, and a set method that takes a string key and an any value and returns boolean. Third, mention that implements enables IDE autocomplete and refactoring safety. Fourth, note that a class can implement multiple interfaces separated by commas.

COMMON WRONG ANSWERS: Confusing implements with extends and saying it creates an inheritance chain or copies prototype methods at runtime. Omitting return types in the example or using incorrect parameter types. Claiming that implements generates runtime validation code. Writing an interface with method bodies. Forgetting that any is the required return type for get and boolean for set. Saying that implements is required to use an interface rather than understanding it is an optional enforcement tool.

LIKELY FOLLOW-UPS: How does implements differ from extends and when would you use one over the other? Can you implement multiple interfaces and what happens if they conflict? What happens if a class implements an interface but is missing a method? How do you handle optional properties in an interface when implementing? What is the difference between an interface and an abstract class?

ONE CONCRETE EXAMPLE: interface ICache { get(key: string): any; set(key: string, value: any): boolean; } class CacheService implements ICache { private store = new Map(); get(key: string): any { return this.store.get(key); } set(key: string, value: any): boolean { this.store.set(key, value); return true; } } This satisfies the contract because both methods are present with matching signatures.

Read the original → typescriptlang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.