How to make an empty createcontext in typescript?

306 Views Asked by At

I keep wanting to use a use cotext hook but i learned to use use context by putting an empty {} in the create context thing. But it is giving me errors. Not assignable to {} and type any not available.

import React from "react";

type data = {
    state?: any;
};

const state = 1;
export const BasicContext = React.createContext<data>(state);

this gave an error

Type '1' has no properties in common with type 'data'.(2559)

How do i fix it? It is weird?

1

There are 1 best solutions below

0
mochaccino On

You're giving it the wrong type. Since you used createContext<data>, it expects an initial value with the type data. Because data is an object type, and you passed a number, TypeScript throws an error.

You can wrap your state in brackets taking advantage of property initializer shorthand to easily create an object that matches the data type:

const state = 1;
export const BasicContext = React.createContext<data>({ state });
//                 same as passing { state: state } - ~~~~~~~~~

Playground