Classes & Interfaces — Series 3

Preview — 3 of 10 questions

javascript
interface Logger {
  prefix: string;
  log(message: string): void;
}

class ConsoleLogger implements Logger {
  prefix = "[app]";
}
ACompiles fine — a class only has to implement the properties, not the methods
BCompiles fine — log is treated as optional because it has no body in the interface
CCompile-time error — ConsoleLogger is missing the log method required by Logger
DCompile-time error — an interface may not mix properties and methods

javascript
class Session {
  userId?: string;
}

const s = new Session();
console.log(s.userId.length);
ACompile-time error — s.userId is string | undefined, so .length may not exist
BCompiles fine and logs 0
CCompiles fine and logs undefined
DCompile-time error — a class field may not be declared optional

javascript
interface HasId {
  id: string;
}

class Entity implements HasId {}
ACompiles fine — implements copies id into the class
BCompiles fine — id is inherited and initialized to undefined
CCompiles fine, but id is only available on instances typed as HasId
DCompile-time error — implements only checks the class; the members must still be declared on it

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.