DEV Community

Discussion on: TypeScript: type compatibility vs duck typing

Collapse
 
tqbit profile image
tq-bit

This is interesting indeed. Even according to my VSCode Tooltip, Pizza is indeed still typed as Pizza and not as Beer.

Image description

You could mitigate this problem by using classes:

Image description

Collapse
 
mistomin profile image
Mikhail Istomin

Thanks for your point! However I don't agree that using classes can mitigate the problem.
In your example the TS error is not caused by classes. The thing is Pizza and Beer are not compatible due to isFrozen property. Once we make classes compatible the same issue with the discount price occurs. Here is TypeScript Sandbox with class-based example.

Collapse
 
tqbit profile image
tq-bit

Well observed. You still need to put some elbow greese into properly distinguishing the two from one another.

I took your example and extended it a bit using polymorphism as I missed to show it in my sloppy example above. Now even though the two classes are compatible, you will still receive the proper price for each product.

Sandbox