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
6 Replies
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?
Hmm it still doesnt work
But i can just stick with //@ts-expect-error for now
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.
You can also provide another optional chaining operator to the array access:
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. 🙂
It worked thanks!
I got to figure out all these typescript quirks lol