Union & Intersection Types

Preview — 3 of 10 questions

What's the difference between these two approaches?

javascript
interface User {
  name: string;
  email: string;
  age: number;
}

// Approach A: optional fields
interface UserUpdate {
  name?: string;
  email?: string;
  age?: number;
}

// Approach B: utility type
type UserUpdateB = Partial<User>;
AThey are identical — same result
BPartial<User> also makes nested properties optional; the manual version doesn't
CPartial<T> makes properties null, not optional
DThey are identical in this case, but Partial<T> stays in sync if User changes — the manual version would need updating

What's the limitation of Readonly<T>?

javascript
interface Config {
  server: { host: string; port: number };
  features: string[];
}

const config: Readonly<Config> = {
  server: { host: "localhost", port: 3000 },
  features: ["darkMode", "notifications"],
};

config.server = { host: "other", port: 8080 };  // (A)
config.server.host = "other";                    // (B)
config.features.push("newFeature");              // (C)
config.features = [];                            // (D)
AAll four lines cause compile errors
B(A) and (D) cause errors; (B) and (C) are allowed — Readonly is shallow
C(A) causes an error; (B), (C), and (D) are allowed
DNone cause errors — Readonly is informational only

What does TypeScript know inside each branch?

javascript
function formatValue(value: string | number | boolean): string {
  if (typeof value === "string") {
    return value.toUpperCase();   // A
  } else if (typeof value === "number") {
    return value.toFixed(2);      // B
  } else {
    return value ? "Yes" : "No";  // C — what is value's type here?
  }
}
Avalue in branch C is boolean | string | number — TypeScript doesn't narrow
Bvalue in branch C is boolean — TypeScript eliminates string and number
Cvalue in branch C is never — all cases are exhausted
Dvalue in branch C is unknown

Sign up free to play

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