你可以在withButton
属性的值为false
时将其设置为必填,这样它就不会与缺少它的情况匹配:
type MyComponentProps = { isOpen: boolean } & (
| ({ withButton?: true | undefined | never } & { buttonText: string }) // If withButton prop is true or missing, buttonText prop is required
| ({ withButton: false } & { buttonText?: never }) // If withButton prop is false, buttonText prop is forbidden (or at most undefined)
)
现在,当缺少withButton
props 时,TypeScrip会正确地发出警告,但同时也会缺少buttonText
props (即现在需要):
const AnotherComponent = () => {
return (<>
<MyComponent isOpen={false} />
{/*~~~~~~~~~ Property 'withButton' is missing in type '{ isOpen: false; }' but required in type '{ withButton: false; }'.(2322) */}
<MyComponent withButton={true} isOpen={false} />
{/*~~~~~~~~~ Property 'buttonText' is missing in type '{ withButton: true; isOpen: false; }' but required in type '{ buttonText: string; }'.(2322) */}
<MyComponent withButton={false} buttonText="should not be there" isOpen={false} />
{/*~~~~~~~~~ Type 'string' is not assignable to type 'undefined'.(2322) */}
<MyComponent withButton={false} isOpen={false} />{/* Okay */}
<MyComponent withButton={false} buttonText={undefined} isOpen={false} />{/* Okay */}
<MyComponent withButton={true} buttonText="okay" isOpen={false} />{/* Okay */}
<MyComponent withButton={undefined} buttonText="okay as well" isOpen={false} />{/* Okay */}
</>)
}
Playground Link
<MyComponent isOpen={false} />
表示期望withButton
,但我希望它期望buttonText
如果您的意思是希望TS错误提示大约buttonText
而不是withButton
,那么只需确保将您希望TS默认用于提示的类型放在联合的最后:
type MyComponentProps = { isOpen: boolean } & (
| ({ withButton: false } & { buttonText?: never }) // If withButton prop is false, buttonText prop is forbidden (or at most undefined)
// Put last in union the type that you want to hint to by default
| ({ withButton?: true | undefined | never } & { buttonText: string }) // If withButton prop is true or missing, buttonText prop is required
)
const AnotherComponent = () => {
return (<>
<MyComponent isOpen={false} />
{/*~~~~~~~~~ Property 'buttonText' is missing in type '{ isOpen: false; }' but required in type '{ buttonText: string; }'.(2322) */}
<MyComponent buttonText="okay as well again" isOpen={false} />{/* Okay */}
</>)
}
Playground Link个