打字稿:与React传播道具不兼容的类型

时间:2018-04-05 00:27:33

标签: reactjs typescript

我遇到了输入错误,特别是当我将其传递给React组件时,我会分散道具。

type FooLevel = 1 | 2 | 3

interface FooProps {
  fooLevel: FooLevel;
}

// Typing for a SFC
const Foo = ({
  fooLevel
}: FooProps) => {
  return (
    <div>
      <span>Your foo level {fooLevel}</span>
    </div>
  )
}

// Foo invocation: 
const props = { fooLevel: 1 }
<Foo fooLevel={1} />   // this works
<Foo {...props} />     // error - Type 'number' is not assignable to type 'FooLevel'

看起来无法将numberFooLevel联系起来。这是设计的吗?有没有办法绕过这个问题?

3 个答案:

答案 0 :(得分:0)

我通过将1投射到FooLevel来实现这一目标。虽然我觉得这不应该是一个问题。

答案 1 :(得分:0)

您可以手动将props投射到FooProps1 as FooLevel

type FooLevel = 1 | 2 | 3;

interface FooProps {
    fooLevel: FooLevel;
}

const Foo = (props: FooProps) => (
    <div>
        <span>Your foo level {props.fooLevel}</span>
    </div>
);

const myProps: FooProps = { fooLevel: 1 };

const app = props => (
    <div>
        <Foo fooLevel={1 as FooLevel} />
        <Foo {...myProps} /> 
    </div>
);

答案 2 :(得分:0)

您可以通过手动设置props的类型来解决此问题,因为它被推断为数字类型而不是FooLevel

const props: FooProps = { fooLevel: 1 };