具有React useContext的Typescript接口

时间:2019-06-07 16:07:07

标签: javascript reactjs typescript

我有以下三个组成部分:

import React, { Component, ReactNode, useContext } from 'react';

interface Props {
  children: ReactNode | ReactNode[];
};

interface State {
  functionalCookiesOn: boolean;
  performanceCookiesOn: boolean;
};

interface ContextProps {
  functionalCookiesOn: boolean;
  performanceCookiesOn: boolean;
  toggleAllCookies: () => void;
};

const CookiesContext = React.createContext<Partial<ContextProps>>({});

class CookiesProvider extends Component<Props, State> {
  state = {
    functionalCookiesOn: true,
    performanceCookiesOn: true,
  };

  toggleAllCookies = () => {
    this.setState((prevState: State) => ({
      functionalCookiesOn: !prevState.functionalCookiesOn,
      performanceCookiesOn: !prevState.performanceCookiesOn,
    }));
  }

  render() {
    const { children } = this.props;

    const {
      functionalCookiesOn,
      performanceCookiesOn,
    } = this.state;

    const value = {
      functionalCookiesOn,
      performanceCookiesOn,
      toggleAllCookies: this.toggleAllCookies,
    };

    return (
      <CookiesContext.Provider value={value}>
        {children}
      </CookiesContext.Provider>
    );
  }
}


const Settings: React.FunctionComponent = () => {
  const {
    functionalCookiesOn,
    toggleAllCookies,
  } = useContext(CookiesContext);

  return (
    <Switch
      handleChange={toggleAllCookies}
      isOn={functionalCookiesOn}
    />
  );
};


interface SwitchProps {
  handleChange: () => void;
  isOn: boolean;
};

const Switch: React.FunctionComponent<SwitchProps> = ({
  handleChange,
  isOn,
}) => (
  <button onClick={handleChange} type="button">
    {isOn.toString()}
  </button>
);

我得到的错误是在这两行的“设置”组件中:

handleChange={toggleAllCookies}
isOn={functionalCookiesOn}

handleChange的错误是:

Type '(() => void) | undefined' is not assignable to type '() => void'.
  Type 'undefined' is not assignable to type '() => void'.

Type 'boolean | undefined' is not assignable to type 'boolean'.
  Type 'undefined' is not assignable to type 'boolean'.

有人可以解释吗?据我所知,我没有告诉Typescript这些值在任何地方都是可选的,它们是在ContextProvider中分配的值,所以不确定为什么我会收到错误消息。

我尝试用值而不是空对象初始化createContext,但这似乎无济于事。在this link之后,看来我没有做任何不同的事情。

1 个答案:

答案 0 :(得分:0)

只需删除Partial。您是说ContextProps的所有属性都是可选的,这意味着它们可以不确定。