React & TypeScript: Avoid context default value

There’s no way of avoiding declaring the interface and the runtime values, because TS’s types disappear at runtime, so you’re only left with the runtime values. You can’t generate one from the other.

However if you know that you are only ever going to access the context within the TodoContextProvider component you can avoid initialising TodoContext by cheating a little bit and just telling TS that what you’re passing it is fine.

const TodoContext = React.createContext<TodoContext>({} as TodoContext)

If you do always make sure to only access the context inside of TodoContextProvider where todos and setTodos are created with useState then you can safely skip initialising TodoContext inside of createContext because that initial value will never actually be accessed.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)