TypeScript Intermediate — Series 3

Preview — 3 of 10 questions

javascript
function shout(value: string | number) {
  return value.toUpperCase();
}
ACompiles fine — toUpperCase is called on the string member of the union
BCompiles fine, and numbers are converted to their string form first
CCompile-time error — toUpperCase doesn't exist on string | number, and you must narrow before calling it
DCompile-time error — a parameter cannot have a union type

javascript
interface Circle { radius: number }
interface Square { side: number }

function area(shape: Circle | Square): number {
  if ("radius" in shape) {
    return Math.PI * shape.radius ** 2;
  }
  return shape.side ** 2;
}
ACompiles fine — in narrows shape to Circle inside the block and to Square after it
BCompile-time error — in is a runtime operator and has no effect on types
CCompile-time error on shape.side — after the if, shape is still Circle | Square
DCompiles fine, but only because radius and side are both number

javascript
type A = { id: string };
type B = { id: number };
type C = A & B;

const value: C = { id: "abc" };
ACompiles fine — the later member B wins, so id is number... and "abc" is coerced
BCompiles fine — an intersection accepts a value satisfying either side
CCompile-time error on the assignment — id in C is string & number, which reduces to never, so no value satisfies it
DCompile-time error on the type C declaration itself — intersections with conflicting property types are illegal

Sign up free to play

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