【问题标题】:Unable to use 'Helper' booleans in typescript无法在打字稿中使用“助手”布尔值
【发布时间】: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}
    />
)}

【问题讨论】:

标签: reactjs typescript types boolean


【解决方案1】:

您可能会想到 TypeScript 4.4 beta 中的 this new feature。有了这个新功能,您的代码看起来确实像 TypeScript 可以识别别名类型保护并因此成功。

对于你现在的问题,你可以简单地在你的表达式之后添加一个感叹号来告诉 TypeScript“我确定这不是未定义/空的”,例如像这样:

{hasCountry && (
   <PresentationalTextfield
       label="Primary Domicile Country"
       defaultValue={state.insuredInfo.country.Country!}
    />
)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    相关资源
    最近更新 更多