#How to fix "Object is possibly 'undefined'."

28 messages · Page 1 of 1 (latest)

stuck niche
#

what do you want to happen if somebody calls part1([""]) or somesuch?

#

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

light cosmos
#

what if a line in day01.txt doesn't have any numbers?

stuck niche
#

i'd probably add explicit error handling then, possibly like this:

modern locustBOT
#
mkantor#0

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}`)

}
...```

frank topaz
#

It's not saying digits is undefined, it's saying the result of digits.at is potentially undefined.

light cosmos
#

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

stuck niche
#

ah then my error handling is too strict

#

actually wait

light cosmos
#

i don't think it is?

stuck niche
#

if the input is "1" then you'll get 11?

#

because 0 and -1 will refer to the same element

light cosmos
#

it'd be too lenient if that was an error case

frank topaz
#

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.

light cosmos
#

if you don't want to assume, you could also check over digits.length

stuck niche
#

oh wait is this for advent of code or something like that? if so yeah i wouldn't spend time on error handling

frank topaz
#

Yeah, this is AoC day 1.

stuck niche
#

gotcha. i was assuming this was "real" code