如何告诉编译器一个值不能在 react 中未定义?



假设我有一个组件,它将其他组件包裹在react中。


interface LoadWrapperProps {
defined?: boolean;
children: React.ReactNode | React.ReactNode[];
}
export const LoadWrapper = ({loading, children }: LoadWrapperProps) => {
return (
<>
{defined ? (
<div className="flex flex-1 items-center justify-center">
<div className={className}>
<Spinner  />
</div>
</div>
) : (
{ children }
)}
</>
);
};

现在我想像这个一样使用这个

const { data } = useMyQuery<X>(); // data is type X | undefined
<LoadWrapper defined={data}>
<AnotherComponent data={data} /> // here data is type X | undefined but I would like only X since the check has been done on the wrapper.
</LoadWrapper>

有办法做到这一点吗?

我想不出一个保持当前结构不变的好方法,但一个简单的调整就可以做到。请注意,LoadWrapper除了在加载后渲染子元素外什么都不做,除了在其他情况下渲染其他元素(不使用子元素(外什么也不做。因此,与其说它是包装器,不如说它是一个条件元素。考虑将条件移到外部,然后TypeScript将能够理解何时定义了data

export const LoadWrapper = () => (
<div className="flex flex-1 items-center justify-center">
<div className={className}>
<Spinner />
</div>
</div>
);
const { data } = useMyQuery<X>();
return data
? <AnotherComponent data={data} />
: <LoadWrapper />;

或者,如果它被其他JSX包围,你可以做一些类似的事情

<div>{
data
? <AnotherComponent data={data} />
: <LoadWrapper />
}</div>

尽管前面的响应很好,而且在我看来,它有更好的结构,但如果您想保持相同的组件结构,它可以使用data变量上的类型转换,如:

<LoadWrapper defined={data}>
<AnotherComponent data={data as X} /> // or "data as unknown as X"
</LoadWrapper>

最新更新