#How to fix "Object is possibly 'undefined'."
28 messages · Page 1 of 1 (latest)
what about part1(["abc"]), etc?
is anything like that considered an error?
also: could you paste that code here so i don't have to transcribe it?
thanks
what if a line in day01.txt doesn't have any numbers?
i'd probably add explicit error handling then, possibly like this:
Preview:```ts
...
for (const line of input) {
const characters = line.split("")
const digits = characters.filter(
char => char >= "0" && char <= "9"
)
const first = digits.at(0)
const last = digits.at(-1)
if (first === undefined || last === undefined) {
throw new Error("invalid input")
}
sum += parseInt(`${first}${last}`)
}
...```
It's not saying digits is undefined, it's saying the result of digits.at is potentially undefined.
it doesn't work, that never passes.
digits is always an array, which is truthy
btw, how do you want to handle a line having only 1 digit
is that a valid case or an error case?
aight
i don't think it is?
if the input is "1" then you'll get 11?
because 0 and -1 will refer to the same element
it'd be too lenient if that was an error case
Yeah, that's correct
If you want to handle the error you can. You also kinda don't have to.
Honestly, digits.at(0)! + digits.at(-1)! and assuming the puzzle input is valid is a reasonable choice.
Or, TBH, what I did was:
const calibrationValue = `${digits.at(0)}${digits.at(-1)}`;
And that's sidestepped the issue since template interpolations isn't strict about undefined checking.
if you don't want to assume, you could also check over digits.length
oh wait is this for advent of code or something like that? if so yeah i wouldn't spend time on error handling
Yeah, this is AoC day 1.
gotcha. i was assuming this was "real" code