DEV Community

Discussion on: Catching bugs with stricter TypeScript

Collapse
 
juliang profile image
Julian Garamendy

Hi! Thank you. This example is not literally the original code because I'm not allowed to share it.

Where do you suggest having a string literal?

Collapse
 
dorshinar profile image
Dor Shinar • Edited

I'd cast the return value of getMessageIdFromSomeObscureLogic() to a string literal like so:
type messageTypes = "success" | "error" | "warning" | "bananas" | etc....
And I'd type the messages object like so:
const messages: [key in messageTypes]: string;

Thread Thread
 
juliang profile image
Julian Garamendy • Edited

Yes! that would work as well. And it results in a better error report:

  1. The error now is on the messages object declaration (where the banana property is missing) as opposed to where we try to access it by key messages[id]
  2. The error message now reads "Property 'bananas' is missing..." even with TypeScript 2.4. ✅