我<If />
使用React 创建了一个简单的功能组件:
import React, { ReactElement } from "react";
interface Props {
condition: boolean;
comment?: any;
}
export function If(props: React.PropsWithChildren<Props>): ReactElement | null {
if (props.condition) {
return <>{props.children}</>;
}
return null;
}
它使我可以编写更简洁的代码,例如:
render() {
...
<If condition={truthy}>
presnet if truthy
</If>
...
在大多数情况下,它工作良好,但是当我想检查例如是否未定义给定变量然后将其作为属性传递时,这便成为问题。我举一个例子:
假设我有一个名为的组件<Animal />
,它具有以下属性:
interface AnimalProps {
animal: Animal;
}
现在我有另一个组件,它呈现以下DOM:
const animal: Animal | undefined = ...;
return (
<If condition={animal !== undefined} comment="if animal is defined, then present it">
<Animal animal={animal} /> // <-- Error! expected Animal, but got Animal | undefined
</If>
);
正如我所评论的,尽管实际上没有定义动物,但我无法告诉Typescript我已经检查过它。断言animal!
将起作用,但这不是我想要的。
有任何想法吗?
<Animal animal={animal as Animal} />
{animal !== undefined && <Anibal animal={animal} />}
会工作