TS2339

Property 'width' does not exist on type 'Shape'.

Broken Code ❌

type Shape = {
  kind: 'rectangle' | 'square';
};
 
type Rectangle = {
  kind: 'rectangle';
  width: number;
  height: number;
} & Shape;
 
type Square = {
  kind: 'square';
  size: number;
} & Shape;
 
function handleShape(shape: Shape): void {
  switch (shape.kind) {
    case 'rectangle':
      console.log(shape.width);
      break;
    case 'square':
      console.log(shape.size);
      break;
  }
}

Fixed Code ✔️

You can create discriminated unions by sharing a single field (e.g. kind) in your type definitions and using a union type in connection with a switch-case statement that helps the TypeScript compiler to distinguish the different types:

type Rectangle = {
  kind: 'rectangle';
  width: number;
  height: number;
};
 
type Square = {
  kind: 'square';
  size: number;
};
 
type Shape = Rectangle | Square;
 
function handleShape(shape: Shape): void {
  switch (shape.kind) {
    case 'rectangle':
      console.log(shape.width);
      break;
    case 'square':
      console.log(shape.size);
      break;
  }
}

Property 'pop' does not exist on type 'readonly [1, 2, 3]'.

Broken Code ❌

const array = [1, 2, 3] as const;
array.pop();

When using a const assertion on an array, then your array becomes readonly (immutable), so you cannot modify its elements using in-place operations such as pop. You will have to make your array mutable:

const array: number[] = [1, 2, 3];
array.pop();