Undefined TypeScript error

kind of a nooby question but my fool proof solution of adding the null operator when ever this happens has failed me. I appreciate the help :3
No description
6 Replies
TrialEnjoyer
TrialEnjoyer•8mo ago
Add a fallback or add an if statement to make sure its defined. Or if you feel its too tedious, theres always //@ts-expect-error So like add const Fallback = (whatever number); then at the end of skillRating statement, add ?? Fallback - or something alike. Would that work for you?
NeoFox
NeoFox•8mo ago
Hmm it still doesnt work
No description
NeoFox
NeoFox•8mo ago
But i can just stick with //@ts-expect-error for now
Jay
Jay•8mo ago
It seems to be happening because skillRating is the one that can be undefined not just the formdata, you could add an assert if you'd be sure that the index would exist every time. by doing let skillRagin = formData?.skillRating![index] notice the exclamation before accessing indexed value. For more context here's a link to ts playground: https://www.typescriptlang.org/play?#code/MYewdgzgLgBAZiATgWwCIEMroFwwN4QDWAlgDakBKmxYA5gPzZgCuyARgKaIDaAugL4wAvPiJlK1Otj78AULNIdYNACYcAHsJgAGeYtiJJtCFoQoMWAHRjyVKDVoBCbqo28YAeg8wAKgAsOGHQICC5YEAAHLkwkGGR0Qg4TQ3s6EygQGE4YEDgYKABPKJgWdi5ZIA. Lmk if this helps.
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
bythewayitsjosh
bythewayitsjosh•8mo ago
You can also provide another optional chaining operator to the array access:
const fallback = 1
let skillRating = formData?.skillRating?.[index] ??
fallback
const fallback = 1
let skillRating = formData?.skillRating?.[index] ??
fallback
In general I prefer using optional chaining and fallbacks rather than assuming / asserting that something will be defined if Typescript can't tell you for sure it will be. But I think either is fine. 🙂
NeoFox
NeoFox•8mo ago
It worked thanks! I got to figure out all these typescript quirks lol
Want results from more Discord servers?
Add your server