Skip to content

QuizNot attempted

Structural typing surprise

Does this compile?
type User = { name: string };
const raw = { name: 'Ann', password: 'x' };
const u: User = raw; // (1)
const v: User = { name: 'Bo', password: 'y' }; // (2)
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • (1) compiles, (2) errors (excess property check on fresh object literals)
  • TS is structural, so raw (which has at least name: string) is a valid User in (1)
  • excess property checks run only on fresh object literals written directly at the assignment, so password errors in (2).
  • Not both compile: misses the excess property check.
  • Not both error: extra properties on a non-literal are fine.
  • Not (1) errors, (2) compiles: exactly backwards.