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 ; } }