Classes & Interfaces

Preview — 3 of 10 questions

What is the purpose of an interface in TypeScript?

javascript
interface User {
  id: string;
  name: string;
  email: string;
}
AIt creates a JavaScript class at runtime
BIt creates a singleton object
CIt defines the shape (contract) of an object — compile-time only, no runtime artifact
DIt is identical to type in every way

What does the ? modifier mean on an interface property?

javascript
interface Config {
  host: string;
  port?: number;
  debug?: boolean;
}
Aport must be provided but can be undefined
Bport defaults to 0 if not provided
Cport is read-only
Dport is optional — it can be omitted entirely or provided as number | undefined

What does implements guarantee?

javascript
interface Serializable {
  serialize(): string;
  deserialize(data: string): void;
}

class UserSession implements Serializable {
  serialize(): string { return JSON.stringify(this); }
  deserialize(data: string): void { Object.assign(this, JSON.parse(data)); }
}
AUserSession inherits the method implementations from Serializable
BUserSession can only be used where Serializable is expected
CTypeScript verifies at compile time that UserSession provides all methods declared in Serializable
Dimplements creates a prototype chain between the interface and the class

Sign up free to play

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