Deno adds "| undefined" to everything
When trying to call a value from an object or Record directly by its key, deno says object might be undefined for some reason.
gives me
why.
3 Replies
i'm very new to deno as well as programming in general, so please be gentle if it's a very obvious answer that i should have realised myself 😅
The record type is just defining object properties which function as a dictionary. In a dictionary it's possible to try to get a value which doesn't exist. For example, in your current code
objectList['itemOne']
returns a number array, but you can also do a call such as objectList['itemThree']
which doesn't exist, and will return undefined
. That's why records have return types of whatever value or undefined.
When you know for a fact that you're going to get an array back (or any other type), you can use typecasting to tell the compiler to stop warning you about the possibility for runtime errors using the as
keyword:
const numberArray: number[] = objectList['itemOne'] as number[]
Although I will note that I do not get any typescript errors when running your original code normally. This behavior is enabled by turning on additional features of the typescript compiler. Specifically I am able to get a similar result by adding this to the deno.json
:
huh. i wonder why that's there by default
the way i create my projects is via
deno run -A npm:create-vite-extra@latest
and selecting the deno-solid option
not sure if that's the recommended way
thanks for the tip though, it's just weird to me that it wouldn't just annotate if i used an incorrect value