CodePark/ questions / any, unknown & never
START PRACTICINGPRACTICE
Frontend question · TypeScript › any, unknown & never

Which lines produce a compile error?

function handle(value: unknown) {
  const a: unknown = value;          // Line 2
  const s: string = value;           // Line 3
  if (typeof value === "string") {
    value.toUpperCase();             // Line 5
  }
  value.toString();                  // Line 7
}
Lines 3 and 7

Lines 3 and 7 error. You cannot assign an unknown value to string or read its members until you narrow it. Line 3 assigns it to string, so it errors.

"Lines 3, 5 and 7" is wrong because Line 5 is inside a
typeof check, where value is a string. "Only Line 7" is wrong because Line 3 also errors. Line 7 is outside the check, so even toString() is rejected.