Noite
Noite•4mo ago

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.
const objectList: Record<string, number[]> = {
'itemOne': [1, 2, 3],
'itemTwo': [4, 5, 6]
}

const numberArray: number[] = objectList['itemOne']
const objectList: Record<string, number[]> = {
'itemOne': [1, 2, 3],
'itemTwo': [4, 5, 6]
}

const numberArray: number[] = objectList['itemOne']
gives me
Type 'number[] | undefined' is not assignable to type 'number[]'.
Type 'undefined' is not assignable to type 'number[]'.deno-ts(2322)
Type 'number[] | undefined' is not assignable to type 'number[]'.
Type 'undefined' is not assignable to type 'number[]'.deno-ts(2322)
why.
3 Replies
Noite
NoiteOP•4mo ago
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 😅
John Adams
John Adams•4mo ago
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:
"compilerOptions": {
"noUncheckedIndexedAccess": true
}
"compilerOptions": {
"noUncheckedIndexedAccess": true
}
Noite
NoiteOP•4mo ago
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

Did you find this page helpful?