如何使用条件React JSX组件取悦TS编译器



我看到了使用React组件使JSX中内联的条件语句和ternaries更可读的模式。但是,如果有人对TS相关的";"问题";使用这种方法。

所以,假设我有我的组件<MyComponent />,它被定义为它需要一个道具foo。这个道具一定是一根绳子。

type Props = { foo: string};
const MyComponent: FC<Props> = ({ foo }) => ...

然后,我有一个包装器组件来帮助我使一些条件语句更容易推理(有时(;

type Props = { condition: boolean};
const Conditional: FC<Props> = ({ condition, children }) => (condition ? <>{children}</> : null);

现在,示例A有效(ofc…(,但示例B无效。也许有人知道确切的原因,我可能有一些猜测,但对React还不太满意;(当然,更有趣的是,也许有人知道如何让例子B发挥作用?

Example A;
{bar && <MyComponent foo={bar} />}
Example B;
<Conditional condition={bar!==undefined}>
<MyComponent foo={bar} />
</Conditional>

B给出错误;Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2322)

通过使用类似的!,可以用一种简单的方法告诉typescript编译器bar值是不可为null的

// Example B;
<Conditional condition={bar!==undefined}>
<MyComponent foo={bar!} /> // notice the exclamation mark here
</Conditional>

TypeScript似乎没有意识到您已经在通过使用Conditional组件来保证bar变量是未定义的。

有几种方法可以解决这个问题:您可以使用非空断言运算符

<Conditional 
condition={bar /* You can simplify this and do a truthy check*/}
>
<MyComponent foo={bar! /* Note the exclamation mark */} />
</Conditional>

您也可以尝试类型断言,告诉typescript变量是特定类型的。

<Conditional 
condition={bar}
>
<MyComponent foo={bar as string} />
</Conditional>

最新更新