Typescript error code TS7053 occurs when an element is detected to have an implicit 'any' type due to an expression of a different type

I encountered an issue with the provided example.

I'm uncertain about how to resolve it.

Your assistance would be greatly appreciated.


type TestValue = {
  value: string;
};

type FirstTest = {
  type: 'text';
  text: TestValue[];
};

type SecondTest = {
  type: 'heading';
  heading: TestValue;
};

type Test = FirstTest | SecondTest;

const firstTest: Test = {
  type: 'text',
  text: [
    {
      value: 'Text!!',
    },
  ],
};
const secondTest: Test = {
  type: 'heading',
  heading: {
    value: 'heading!!',
  },
};

const foo = (data: Test) => {
  const { type } = data;

  const content = data[type]; //Encountering error TS7053: Element implicitly has an 'any' type because expression of type '"text" | "heading"' can't be used to index type 'Test'.   Property 'text' does not exist on type 'Test'.

  switch (type) {
    case 'heading':
      return content.value;
    case 'text':
      return content[0].value;
  }
};

Unfortunately, I am faced with the error

TS7053: Element implicitly has an 'any' type because expression of type '"text" | "heading"' can't be used to index type 'Test'.   Property 'text' does not exist on type 'Test

Executing the foo function results in a type validation issue.

Answer №1

If you want to make the most of the discriminated union type, ensure that you only try to access data[type] within the corresponding block where type was discriminated. For example, within your switch statement:

const foo = (data: Test) => {
  const { type } = data;
  let content: FirstTest['text'] | SecondTest['heading']

  type // "text" | "heading"
  data // FirstTest | SecondTest
  data[type] // invalid as neither "text" nor "heading" appear on both FirstTest and SecondTest

  switch (type) {
    case 'heading':
      type // "heading"
      data // SecondTest
      content = data[type] // valid as SecondTest['heading'] exists
      return content.value;
    case 'text':
      type // "text"
      data // FirstTest
      content = data[type] // valid as FirstTest['text'] exists
      return content[0].value;
  }
};

In order to simplify, you can skip creating the content variable completely:

const foo = (data: Test) => {
  const { type } = data;

  switch (type) {
    case 'heading':
      return data[type].value; // valid
    case 'text':
      return data[type][0].value; // valid
  }
};

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

Custom HTML binding in expanding rows of Angular 2 DataTables

I am currently working on implementing a data table feature that allows for an extended child row to be displayed when clicking the + icon. This row will show additional data along with some buttons that are bound via AJAX before transitioning to Angular 2 ...

Is there a way to access the value of an IPC message beyond just using console log?

I am developing an app using electron and angular where I need to send locally stored information from my computer. I have successfully managed to send a message from the electron side to the angular side at the right time. However, I am facing issues acce ...

Error encountered in Angular Html2Pdf: Unable to assign the 'adoptedStyleSheets' attribute on 'ShadowRoot' due to DOMException

Looking for assistance in implementing html2pdf with Angular 12 to convert specific parts of an HTML page into a downloadable PDF. ERROR MESSAGE An error occurred while trying to execute the code: index-7a8b7a1c.js:150 Uncaught (in promise) DOMExce ...

The CSS "mask" property is experiencing compatibility issues on Google Chrome

Hey there! I've recently developed a unique progress bar component in React that showcases a stunning gradient background. This effect is achieved by utilizing the CSS mask property. While everything runs smoothly on Firefox, I'm facing a slight ...

An issue occurred while trying to run Ionic serve: [ng] Oops! The Angular Compiler is in need of TypeScript version greater than or equal to 4.4.2 and less than 4.5.0, but it seems that version 4

Issue with running the ionic serve command [ng] Error: The Angular Compiler requires TypeScript >=4.4.2 and <4.5.0 but 4.5.2 was found instead. Attempted to downgrade typescript using: npm install typescript@">=4.4.2 <4.5.0" --save-dev --save- ...

Receiving errors in React/TS/material-ui when attempting to use a variable as a value for a grid property. Messages include "No overload matches" and "Type 'number' is not assignable to type..."

tl;dr: When using a variable as the value of a grid xs property in JSX, material-ui throws a TS error. I'm working on implementing grids in material-ui with React/TypeScript. The goal is to make the width of a specific element dependent on the quant ...

NextJS Typescript Player

Encountering an issue during the build process, specifically with the error in audioRef.current.play(). The error message indicates that there is no play function available. I attempted to use an interface but it seems to not accept boolean values. Could ...

What is the best way to convert the reader.result into a string?

Whenever I attempt to upload an image on Angular, I encounter an error with reader.result in the TypeScript file below. How can I resolve this issue? I even included console.log(image) in the onImagePicked function but it doesn't display anything in ...

When an import is included, a Typescript self-executing function will fail to run

Looking at this Typescript code: (()=> { console.log('called boot'); // 'called boot' })(); The resulting JavaScript is: (function () { console.log('called boot'); })(); define("StockMarketService", ["require", "exp ...

Ionic Framework: Implementing a search bar in the navigation bar

I am looking to include a search icon in the navbar of my Ionic project <ion-navbar> <ion-buttons left> <button ion-button menuToggle> <ion-icon name="menu"></icon-icon> </button> </ion-bu ...

Unable to retrieve React state within the callback function

As I work with the following components: const ParentComponent: React.FC = () => { // Setting newType to some value within the code const [newType, setNewType] = useState<any>(undefined); // Enabling addEdge to true in another part o ...

Cannot establish a connection with Socket.IO

I've encountered an issue with establishing a connection to Socket.IO in my node server. Although the server starts successfully with Socket.IO, I am not seeing any console logs when trying to connect to Socket. this.server.listen(this.port, () => ...

Sharing precise API information between React components in React Components

I am currently learning react and facing an issue with sending data to other component files. I am trying to verify a user login from a backend API within an if statement, and if successful, I want to send the user ID to another component file. However, ...

Is it possible to apply search filters within a child component in Angular?

I have a situation where I am passing data from a parent component to a child component using *ngFor / @input. The child component is created multiple times based on the number of objects in the pciData array. pciData consists of around 700 data objects, ...

Puzzled by the specialized link feature

As I delve into the world of React and Next.js, I find myself working on the link component. Initially, I had a grasp on basic routing in next.js which seemed pretty straightforward. However, things took a confusing turn when I stumbled upon this code: imp ...

Encountering an error in TypeScript: Attempting to define type files for a third-party library triggers the TS2709 error when attempting to use the 'Optional' namespace as a type

Currently, I'm in the process of creating type files for a third-party library called optional-js. The structure is as follows: index.js var Optional = require('./lib/optional.js'); module.exports = { empty: function empty() { ...

What causes the select dropdown to display an empty default in Angular 8 following an HTTP request?

I have created a simple HTML code to populate array elements in a dropdown list, with the default value being fetched from an HTTP service during the ngOnInit lifecycle hook. However, I am encountering an issue where the default value is displayed as empty ...

Incorporate a generic type into a React Functional Component

I have developed the following component: import { FC } from "react"; export interface Option<T> { value: T; label: string; } interface TestComponentProps { name: string; options: Option<string>[]; value: string; onChang ...

Can someone explain how to showcase a collection attribute in Angular?

I am working with a collection of objects called "ELEMENT_DATA". Each object in the collection has an attribute named "Activite", which is also a collection. My goal is to display this attribute in a specific way. Below is my app.component.ts: export cla ...

Error message stating: rxjs and firebase encountered a TypeError when attempting to add property 0 because the object is not

My angular application interacts with firebase firestore as the backend database. I am working on a function to retrieve document snapshots from firestore in a generic way. Here is the code snippet where I encounter an error: /** * Get a 'liste ...