Ollie
Ollie

Reputation: 1134

Unable to use 'Helper' booleans in typescript

I'm trying to use 'helper booleans'. I'm showing some TSX, but I don't think it changes anything.

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

...

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

But despite the helper being truthy, defaultValue still complains that the value might be undefined.

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; }'

Ditching the helper method, and declaring it inline works just fine.

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

Upvotes: 1

Views: 85

Answers (1)

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

You might be thinking of this new feature in the TypeScript 4.4 beta. With that new feature, your code does look like TypeScript would recognize the aliased type guard and therefore succeed.

For your problem right now, you can simply add an exclamation mark after your expression to tell TypeScript "I'm sure this isn't undefined/null", e.g. like this:

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

Upvotes: 2

Related Questions