DEV Community


Discussion on: Discoveries I made while using Typescript and React

ybogomolov profile image
Yuriy Bogomolov

Some more tips:

  1. Avoid using any at all costs! You will benefit from specifying types more precisely, and if you happen not to know the exact type, you can use unknown type – which is similar to any, but it doesn't allow code to escape the TypeScript type system. More on that:

  2. Never-ever use Function and object types. It's the same thing as with any: you lose all type safety this way. For your example it's better to use React.EventHandler<T> type and its specializations like MouseEventHandler, PointerEventHandler and so on, or specify function signatures explicitly:

type TListenerTypes = 'onload' | 'progress' | 'error';
type TListeners = Record<TListenerTypes, React.MouseEventHandler>;

// or:

type TListeners = Record<TListenerTypes, ((e: Event) => void)>;

If you want to dive deeper in type-safe TypeScript development, please check out my article (it's currently on Medium, but if an interest arise, I'll re-post it here):