【发布时间】:2021-09-30 17:54:30
【问题描述】:
我正在尝试使用“帮助布尔值”。我正在展示一些 TSX,但我认为它不会改变任何东西。
const hasCountry = state.insuredInfo.country?.Country;
...
{hasCountry && (
<PresentationalTextfield
label={'Primary Domicile Country'}
defaultValue={state.insuredInfo.country.Country}
/>
)}
但尽管助手是真实的,defaultValue 仍然抱怨值 可能 未定义。
键入'字符串 | undefined' 不可分配给类型 'string'。 类型“未定义”不可分配给类型“字符串”.ts(2322) index.tsx(26, 3):预期类型来自属性“defaultValue”,该属性在此处声明类型为“IntrinsicAttributes & { label: string;默认值:字符串; }'
放弃辅助方法,并将其声明为内联就可以了。
{state.insuredInfo.country?.Country && (
<PresentationalTextfield
label={'Primary Domicile Country'}
defaultValue={state.insuredInfo.country.Country}
/>
)}
【问题讨论】:
-
hasCountry不是 type predicate,只是一个布尔值 - 它不会缩小state.insuredInfo.country.Country的类型。 -
您能否发布一个minimal reproducible example,它可以放入像the TypeScript Playground 这样的独立IDE 中? TS4.4 which tracks aliased conditions 中有一个新功能可以满足您的需求,但如果没有可重现的示例,我无法确定。
标签: reactjs typescript types boolean