无法在打字稿中使用 'Helper' 布尔值

Unable to use 'Helper' booleans in typescript

我正在尝试使用 'helper booleans'。我正在展示一些 TSX,但我认为它不会改变任何东西。

const hasCountry = state.insuredInfo.country?.Country;

...

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

但是尽管 helper 是真实的,defaultValue 仍然抱怨值 可能 未定义。

Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2322) index.tsx(26, 3): The expected type comes from property 'defaultValue' which is declared here on type 'IntrinsicAttributes & { label: string; defaultValue: string; }'

放弃辅助方法,将其声明为内联就可以了。

{state.insuredInfo.country?.Country && (
   <PresentationalTextfield
       label={'Primary Domicile Country'}
       defaultValue={state.insuredInfo.country.Country}
    />
)}

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

对于您现在的问题,您只需在表达式后添加一个感叹号即可告诉 TypeScript“我确定这不是 undefined/null”,例如像这样:

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