'Accessing an array by index won't warn about possibility of undefined?
Is there a way to make sure, that the compiler will cry every time I try to access an array by index?
In my example, I explicitly say, that the record could be undefined, but the compiler still won't cry.
type MyDataType = { id: number, name: string };
const array: MyDataType[] = [
{ id: 1, name: "Hey folks" },
]
const record: MyDataType | undefined = array[1];
What is the best approach to make it evident, that array[index] can return undefined or maybe even null?
Solution 1:[1]
type MyDataType = { id: number, name: string };
type NullableArray<T> = {
[K in number]: T | undefined
}
const array: NullableArray<MyDataType> = [
{ id: 1, name: "Hey folks" },
]
const record: MyDataType = array[1];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dean Xu |
