我遇到了输入错误,特别是当我将其传递给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'
看起来无法将number
与FooLevel
联系起来。这是设计的吗?有没有办法绕过这个问题?
答案 0 :(得分:0)
我通过将1
投射到FooLevel
来实现这一目标。虽然我觉得这不应该是一个问题。
答案 1 :(得分:0)
您可以手动将props
投射到FooProps
和1 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 };