Limiting the data types of array elements applies to variables, not to indexes

type Soccer = { ball: string }
type Basketball = { jump: string }
type Data = Soccer[] | Basketball[]

if ('ball' in data[index]) { // type guard not effective here.
  <MyComponent something={data[index]} /> // data: Soccer[] | Basketball[]
}
const resultObj = data[index] // storing indexed element into variable.

if ('ball' in resultObj)
  <MyComponent resultObj={resultObj} /> // works with variable
if (data)
  <MyComponent resultObj={data[index]} /> // does not work with index.

I am perplexed by how assigning data[index] to a variable resolved the type narrowing issue. I anticipated that 'ball' in data[index] would function, but it did not..

Answer №1

If the index is not a literal, type narrowing will not work (I assume that in your example, the variable index is of type number).

Your current workaround of assigning the value of data[index] to a variable and narrowing it down is the best approach.


To learn more, visit: https://github.com/microsoft/TypeScript/issues/10530

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

Displaying hidden Divs in React Typescript that are currently not visible

I have an array with various titles ranging from Title1 to Title8. When these titles are not empty, I am able to display their corresponding information successfully. Now, my goal is to include a button that will allow me to show all fields. For example, ...

The `note` binding element is assumed to have an unspecified `any` type

I'm encountering an error that I believe is related to TypeScript. The issue arises when trying to work with the following example. I am using a JavaScript server to import some notes. In the NoteCard.tsx file, there is a red line under the {note} cau ...

Is it possible to turn off Angular CLI ng build linting for a specific directory?

I am facing an issue with a specific directory in my project template that I want to exclude from linting. Despite excluding it in both tsconfig and eslint, running eslint works fine but when using ng build, the directory is still included in linting and e ...

Exploring the versatility of Angular 4 by implementing a switch feature with

My goal is to have the menu change based on the click of the "Cadastros" action, but it seems like the issue lies with the "workspaceSelected" property not being visible to all components. I believe the best approach in this situation would be to have the ...

The Angular Progressive Web App functions properly in ng serve mode, but encounters issues when running with http-server

I'm developing a Progressive Web App (PWA) using Angular. Everything was functioning smoothly until out of nowhere, I started encountering a 404 Error whenever I tried to navigate to a new component while serving in dist/project with http-server. Surp ...

Applying Material UI class in React: Troubleshooting an error with your hook call

Recently, I have started using React and encountered an issue with a hook call. I understand the root cause of the problem but unsure how to resolve it without starting from scratch. Here is the snippet of the code: import { Fragment, PureComponent } from ...

Creating a React Native project without the use of TypeScript

Recently I dived into the world of React Native and decided to start a project using React Native CLI. However, I was surprised to find out that it uses TypeScript by default. Is there a way for me to create a project using React Native CLI without TypeS ...

Extract HTML content using CKEditor

Hey there! I'm in need of some help with getting user-entered data from a textarea. I've already attempted using CKEDITOR.instances.editor1.getData() and CKEDITOR.instances.ckeditor.document.getBody.getHtml(), but unfortunately both only return ...

What are the best practices for utilizing fetch() to retrieve data from a web API effectively?

Is there a way to store stock data in stockData and display it in the console upon form submission? Upon submitting the form, I only receive undefined. I suspect this may be due to a delay in fetching data from the API (but not certain). How can I resol ...

What sets TypeScript apart from AtScript?

From what I understand, TypeScript was created by Microsoft and is used to dynamically generate JavaScript. I'm curious about the distinctions between TypeScript and AtScript. Which one would be more beneficial for a JavaScript developer to learn? ...

Improved with TypeScript 4.1: Fixed-Size String Literal Type

The latest updates from the TypeScript team have shown significant improvements in string literal typing (4.1 & 4.2). I'm curious if there's a way to define a fixed length string. For example: type LambdaServicePrefix = 'my-application- ...

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...

Error: Unable to retrieve options using this.getOptions function. This issue is unrelated to Vue, it is occurring within

Required Modules "dependencies": { "express": "^4.17.1", "express-static-gzip": "^2.1.1", "react": "^17.0.2", "react-dom": "^17.0.2", "reac ...

Typescript - ensure only one specific value is in an array of length N

Is there a way to require the 'foo' literal, while allowing the array to have any shape (i.e. not using an X-length tuple with pre-defined positions)? type requireFoo = ??? const works: requireFoo = ['bar','foo'] //This shoul ...

Angular Material's <mat-select> tag allows for the inclusion of an <input> element within it

I am attempting to place an input element inside the mat-select tag of the Angular Material element. However, I am facing an issue where I cannot input any text into the input field inside the select element. Below is the code I am using to search for elem ...

Can you identify the type of component being passed in a Higher Order Component?

I am currently in the process of converting a protectedRoute HOC from Javascript to TypeScript while using AWS-Amplify. This higher-order component will serve as a way to secure routes that require authentication. If the user is not logged in, they will b ...

Encountering a 405 Error While Trying to Detect Location in Angular 7

I encountered an error 405 (Method Not Allowed) when trying to detect the location. Service public fetchWeatherDataByCoordinates(coordinates: ICoordinates): void { console.log("problem here") this.selectedLocationId.next(this.currentCoordinates ...

Updating pointers to elements depending on their current status

I am working with an array and looping through it to create div elements. Depending on whether the divs are 'active' (determined by state), I want to assign them the ref property. The ref is also the parameter for a hook that adds an onclick list ...

encountering issues with configuring TypeScript LSP in NeoVim with the use of the lazy package manager

Encountered an error in nvim when opening a .ts file. Using mason, mason-lspconfig, and nvim-lspconfig for lsp setup. Lua language lsp is functioning properly, but facing errors with ts files as shown in the screenshot below: https://i.stack.imgur.com/gYM ...

Evaluating observables in .pipe angular 8 jasmine

In my component, I have a subscription to triggerRuleExecutionService which is triggered by another component using next(). Within the pipe, I am using switchMap to make an HTTP service call and retrieve data from the database. this.ruleExecutionService ...