[英]Typescript: incompatible types with React spread props
我遇到輸入錯誤,特別是當我將prop傳遞到React Component時散布了prop時。
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
。 這是設計使然嗎? 有沒有辦法解決這個問題?
我通過將1
強制轉換為FooLevel
來使其工作。 盡管我覺得這首先不是問題。
您可以手動將props
投射為FooProps
,將1 as FooLevel
投射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>
);
您可以通過手動設置props
的類型來解決此問題,因為它被推斷為數字類型而不是FooLevel
const props: FooProps = { fooLevel: 1 };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.