Utility Types — Series 2

Preview — 3 of 10 questions

javascript
class Car {
  constructor(public brand: string) {}
}
type CarInstance = InstanceType<typeof Car>;
const c: CarInstance = new Car("Toyota");
const bad: CarInstance = { brand: "Toyota" };
ACarInstance is the constructor function's own type, so neither c nor bad compiles
BCarInstance is Car — the instance type produced when Car is constructed with new — so c compiles fine; bad also compiles fine, since it structurally matches Car's instance shape ({ brand: string })
CCarInstance is typeof Car, so only values actually produced via new Car(...) are accepted, meaning bad fails to compile
DCompile-time error — InstanceType requires an explicit class name argument, not typeof Car

javascript
type AllStatus = "pending" | "active" | "archived" | "deleted";
type ActiveStatus = Exclude<AllStatus, "archived" | "deleted">;
type ArchivedOrDeleted = Extract<AllStatus, "archived" | "deleted">;
AActiveStatus is "archived" | "deleted"; ArchivedOrDeleted is "pending" | "active" — the two utility types are swapped from what their names suggest
BBoth ActiveStatus and ArchivedOrDeleted resolve to the full AllStatus union, unchanged
CActiveStatus is "pending" | "active" — Exclude removes the listed members from the union; ArchivedOrDeleted is "archived" | "deleted" — Extract keeps only the members that match
DBoth resolve to never, since neither utility type works on string-literal unions

javascript
interface Paginated<T extends { id: number } = { id: number }> {
  items: T[];
  page: number;
}
const p1: Paginated = { items: [{ id: 1 }], page: 1 };
const p2: Paginated<{ id: number; name: string }> = {
  items: [{ id: 1, name: "Ana" }],
  page: 1,
};
ABoth compile fine — p1 uses the default type argument { id: number }; p2 explicitly supplies a more specific type that still satisfies the constraint T extends { id: number }
BCompile-time error — a generic type parameter can't have both a constraint (extends) and a default value (=) at the same time
Cp1 compiles fine; p2 is a compile-time error, because a default type argument, once declared, is always used and can't be overridden
DBoth are compile-time errors — interfaces don't support default generic type parameters

Sign up free to play

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