When there are no elements in the array, TypeScript does not perform any type checking

If the array is empty, TypeScript does not perform type checking

Here is my code snippet:

type List = { name: string }[]

const l: List = []

// error
l[0].name

Is there a method to enable TS type checking in this scenario? How can I make TS type checking function properly?

Answer №1

Make sure to activate the noUncheckedIndexedAccess setting within the compilerOptions section of your tsconfig.json.

Once enabled, you will begin receiving TypeScript errors such as

Object is possibly 'undefined'.(2532)
for statements like these.

type List = { name: string }[]

const l: List = []

l[0].name // <-- error

l[0]?.name // <-- no error (ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)

Interactive Playground

It's important to note that the noUncheckedIndexedAccess option does not verify the length of your array; it serves as a reminder that the index being accessed may not exist.


If your array (and its elements) are intended to be immutable, you can also utilize const assertion:

const l = [{ name: 'foo' }] as const

l[0].name // no error
l[1] // error: Tuple type 'readonly [{ readonly name: "foo"; }]' of length '1' has no element at index '1'.(2493)

If you simply wish to have a fixed-length array with mutable elements in TypeScript 4.1 and above, you can achieve this by:

// based on - https://stackoverflow.com/a/52490977

type _TupleOf<T, N extends number, R extends unknown[]> = R['length'] extends N ? Readonly<R> : _TupleOf<T, N, [T, ...R]>
type Tuple<T, N extends number> = N extends N ? (number extends N ? T[] : _TupleOf<T, N, []>) : never

type List = Tuple<{ name: string }, 1>

const l: List = [{ name: 'foo' }]

l[0].name // no error
l[1] // error: Tuple type 'readonly [{ name: string; }]' of length '1' has no element at index '1'.(2493)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging Renderer in Angular 4

Understanding the importance of using a renderer instead of directly manipulating the DOM in Angular2 projects, I have gone through multiple uninstallations, cache clearings, and re-installations of Node, Typescript, and Angular-CLI. Despite these efforts, ...

Exploring the versatility of Angular/Ionic Storage for dynamic data storage

Recently, I encountered an issue with my code where the data selected by the user gets parsed into an array, but there is no way to store this data permanently. As the user navigates away from the component, the data vanishes. I attempted to utilize Ionic ...

Exploring Screen Navigation in React Native using Typescript

Good day, I am currently working on a react native app project. I am trying to create a simple example to better understand how the navigation works, but I am having trouble replicating the example provided in the documentation. Below is an image showing ...

React and TypeScript: Anticipating a function call or assignment but encountered an expression instead

I've developed a signup feature using React and Redux, and have completed all the necessary actions and reducers. However, I encountered the following error: Expected an assignment or function call and instead saw an expression This particular file s ...

The error thrown by Mongoose, stating "TypeError: Cannot read property 'catch' of undefined," is not caught after the data is saved

After updating to Mongoose version 5.0.15, I encountered an error that says TypeError: Cannot read property 'catch' of undefined when trying to save my object with errors found, even though everything was working fine on Mongoose version 4.13.11. ...

Tips for guaranteeing a Typescript string enum with identical key and value pairs

I am looking for a way to create a generic type that verifies certain criteria on an enum: all fields must be strings all values must be equal to their respective keys For example, the following enums would meet the requirements: enum correct1 { bar ...

Can you explain what comes after the equal sign in a TypeScript object?

While browsing through this response on stackoverflow The author answered: // How I usually initialize var foo:IFoo = <any>{}; I attempted to research it online, but unfortunately, I couldn't find any information about it. Could someone expl ...

experimenting with the checked attribute on a radio button with jasmine testing

Currently using Angular 8 with Jasmine testing. I have a simple loop of radio buttons and want to test a function that sets the checked attribute on the (x)th radio button within the loop based on this.startingCarType. I am encountering false and null tes ...

Exploring the capabilities of supertest by testing endpoints in Express with NodeJS

Having trouble setting up a test environment to test my TypeScript Express Node.js endpoints. Here are the packages I've installed: jest ts-jest jest-junit supertest @types/supertest @types/jest This is how my spec file looks like: imp ...

React with TypeScript: The struggle of getting LocalStorage to work

Currently, I am dealing with persistence in a todo application developed using React and TypeScript. To achieve the desired persistence, I have implemented localStorage. Allow me to share some code snippets: const [todos, setTodos] = useState<todoMod ...

Issues with loading Angular 6 project in Internet Explorer 11

My Angular 6 project is successfully loading in Chrome, however it is not working in IE11. I referred to the Stack Overflow question titled Angular 2 / 4 / 5 not working in IE11 for potential solutions, but unfortunately none of them resolved the issue. He ...

Strategies for updating JSON file content as data evolves

I am facing an issue with loading a json file that populates charts. The file is generated from external data sources and stored in the asset directory. Is there a method to automatically load the updated json file? I have attempted to include the code fo ...

There was a DOMException in Angular because the transaction is not active when trying to execute 'getAll' on 'IDBObjectStore'

private get ctxMessage() { const messageTransaction = this.db.transaction('messages', 'readwrite'); const messageStore = messageTransaction.objectStore('messages'); return { messageTransaction, messageStore }; } ...

Ensuring full enum coverage in TypeScript switch/case statements

I have 2 enums Color and Shape. The constant SHAPES_BY_COLOR connects shapes with different colors. In the future, I aim to execute specific actions depending on the selected color and shape using a switch/case statement. Is there a way for TypeScript to ...

An issue arises when trying to group and sum an array of objects due to difficulty converting strings to arrays in TypeScript

Below is the provided code snippet: Definition of Interface - interface IWEXInterface { readonly Date?: string; "Exec Qty"?: string; readonly Expiry?: string; } Data Collection - let data: IWEXInterface[] = [ { Date: &qu ...

Register with your Facebook account - Angular 4 Typescript

After extensive searching, I have yet to find a clear answer to my question... This is my first time delving into the world of Social Networks. I am curious to know if there are options for Facebook and Twitter sign-ins using Typescript. It seems that Go ...

Oops! There was an error: Unable to find a solution for all the parameters needed by CountdownComponent: (?)

I'm currently working on creating a simple countdown component for my app but I keep encountering an error when I try to run it using ng serve. I would really appreciate some assistance as I am stuck. app.module.ts import { BrowserModule } from &apo ...

Using InjectionToken within an Angular APP_INITIALIZER function

I am currently working on implementing an APP_INITIALIZER in my Angular 10 project. The factory function I'm using has multiple dependencies, one of which is an InjectionToken<string>. However, I have encountered an issue when trying to inject i ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

Ensure that the array is completely populated before calling it in Angular

My code starts with an empty array and I need to call a service that works with the populated array. Two service calls are used to populate the array, both fetching elements from an API. The issue is ensuring the last service call waits for the array to be ...