7

I've been struggling to declare the TypeScript types of an initial state of a React Context with our errors. It'll store a list of items, and the initial state should be an empty array.

I've tried many options like using an interface instead of a type, using an object to declare the types of items and setItems, declaring the type exactly as it's inferred, even trying to bypass de type declaration altogether, and I've finally managed to make it work like this:

type Props = [any, any];

export const ListContext = createContext<Partial<Props>>([]);

export const ListProvider = (props: any) => {
  const [items, setItems] = useState([]);

  return (
    <ListContext.Provider value={[items, setItems]}>
      {props.children}
    </ListContext.Provider>
  );
};

I'm not sure if it's the correct way (using any doesn't look like it), and I don't fully understand why it works either.

How can I improve it? Thanks in advance.

1 Answer 1

13

This is the way I approach it:

type Item = {
    example_prop: number;
};

interface ContextProps {
    items: Item[];
    setItems: Function;
}

export const ListContext = createContext<ContextProps>({
    items: [],
    setItems: () => null
});

interface Props {
    some_prop: string;
}

export const ListProvider: React.ComponentType<Props> = props => {
    const { some_prop } = props; // This is here just to illustrate
    const [items, setItems] = useState<Item[]>([]);

    return (
        <ListContext.Provider value={{ items, setItems }}>
            {props.children}
        </ListContext.Provider>
    );
};

As you can see I'm passing an object through the Context. The initial state of this object is set to an empty array and a function which returns null; these two values will be overriden and won't actually pass but are required.

The Props from the component I included some_prop, just to serve as an example. Let me know if something is not clear.

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, thanks for the great example and explanation, it works great!
I want to specify exact parameters for my function. This solution worked really well for me: stackoverflow.com/questions/61333188/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.