TS2339

error TS2339: Property ‘width‘ does not exist on type ‘Shape‘.

Broken Code ❌

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
}
}

TS2339: Property ‘pop‘ does not exist on type ‘readonly [1, 2, 3]‘.

Broken Code ❌

1
2
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:

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