Majkeli
Majkeli

Reputation: 187

TypeScript, undefined value to concrete

How do I get from a potentially undefined value to something I can assign to state? I know the data is there but I can't disable the typescript error by doing a check first.

I'm trying to put staleModes into state so I can render controls for each item:

const temps = useSelector((state: RootState) => selectTemps(selectSlss(state)));

const proposedStates = temps?.proposedStates;

const staleModes = proposedStates?.map(a => a.stale.mode);

const [proposedListStale, setProposedListStale] = useState<string[]>(staleModes);

It complains on staleModes here: useState<string[]>(staleModes);

Error is: Argument of type '(string | undefined)[] | undefined' is not assignable to parameter of type 'string[] | (() => string[])'. Type 'undefined' is not assignable to type 'string[] | (() => string[])'.

Upvotes: 0

Views: 240

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370769

The optional chaining may result in staleModes being assigned undefined. If you really need the optional chaining because the property may not exist, you can alternate with the empty array.

Since mode may also be undefined, alternate it with the empty string:

const staleModes = proposedStates?.map(a => a.stale.mode ?? '') ?? [];

But if you're sure the properties and data exists, then remove the optional chaining and use type assertion instead:

const temps = useSelector((state: RootState) => selectTemps(selectSlss(state)))!;

const staleModes = temps.proposedStates!.map(a => a.stale.mode);

Upvotes: 1

Related Questions