【发布时间】:2021-10-03 12:16:25
【问题描述】:
编译器告诉我TestComponent 内的属性propA 和propB 不存在于类型Props<T> 上。我对条件类型有什么遗漏或误解吗?
import React from 'react';
type PropsBase<T extends boolean | undefined> = {
isA?: T;
};
type PropsA = {
propA: string;
};
type PropsB = {
propB: string;
};
type Props<T extends boolean | undefined> = PropsBase<T> & (T extends false | undefined ? PropsB : PropsA);
function TestComponent<T extends boolean | undefined = true>(props: Props<T>) {
if (props.isA) {
return <>{props.propA}</>; // Property 'propA' does not exist
}
if (!props.isA) {
return <>{props.propB}</>; // Property 'propB' does not exist
}
return <></>;
}
<>
<TestComponent propA="propA" /> // Should be valid
<TestComponent isA propA="propA" /> // Should be valid
<TestComponent isA={false} propB="propB" /> // Should be valid
<TestComponent isA propB="propB" /> // Should be invalid
</>
我的目标是创建一个可扩展和可重用的类型,其属性可以通过泛型来控制。我知道这也是通过联合来完成的,但在它之上构建其他类型并不容易。
【问题讨论】:
标签: typescript typescript-generics react-typescript