Ways to input standard fetch() outcome

type Task = {
  name: string
  category: string
  duration: number
  cost: number
  website: string
  identifier: string
  availability: number
}

async function retrieveOne(): Promise<Task> {
  const apiUrl = "https://www.boredapi.com/api/activity"
  const response: Task = await fetch(apiUrl).then(response => (response.json()))
  // Encountered issue with unsafe assignment of an `any` value.eslint@typescript-eslint/no-unsafe-assignment
  // Any recommendations on how to resolve this?
  return response
}

I received :

Encountered issue with unsafe assignment of an any value.eslint@typescript-eslint/no-unsafe-assignment

Any suggestions on how to rectify this?

Answer №1

Any ideas on how to resolve this issue?

Unfortunately, there is no straightforward solution.

When dealing with dynamic data in operations over the wire, the return type is inherently unpredictable at compile-time. It's impossible to statically determine that. Ideally, the return type of response.json() should be unknown.

The best approach with dynamic data is to implement runtime checks to validate it against the desired schema and then transform the data into type-safe structures:

type Thing = {
  a: string
  b: number
}

async function getTheThing(): Promise<Thing> {
  const resp = await fetch('someurl');
  const data: unknown = resp.json();
  if (typeof data === 'object' && data && 'a' in data && 'b' in data && typeof data.a === 'string' && typeof data.b === 'number') {
    return {
      a: data.a,
      b: data.b
    }
  }

  throw new Error('invalid data!')
}

Playground

Notice that the compiler validates this code without any unsafe casts. Also, consider organizing the conditional logic into a user-defined type predicate for enhanced usability.

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

Exploring an object property in Angular 8 through iteration

I have this object with protected products: protected products: { [key: string]: { color: string, brand: string, }; } = {}; products = { scan12345: {color: "Orange", brand: "X"}, scan13813: {color: "Pink", brand: "X"}, } What is the best way t ...

Modifying the title of a dynamically generated element with a Vuex mutation

I'm facing a confusing issue where I am unable to manipulate the title of a dynamically added element independently. The title seems to change for all elements created in the process. What I am aiming for is to be able to call multiple components and ...

Tips for troubleshooting a Typescript application built with Angular 2

What is the best approach for debugging an Angular 2 Typescript application using Visual Studio Code or other developer tools? ...

Accessing base class properties in Typescript: A comprehensive guide

Although I have seen similar questions on this topic, my issue is unique. I have checked my class and am using it in the same way as others who have encountered similar problems. I extended class A into class B, but for some reason I cannot access A's ...

Instantiate a child class within an abstract class by utilizing the keyword "this"

Within my code, there is an abstract class that uses new this(). Surprisingly, this action is not creating an instance of the abstract class itself but is generating an instance of the class that inherits from it. Even though this behavior is acceptable i ...

Tips for displaying backend error messages on the frontend

I am facing an issue with returning error messages from the backend to the frontend in my Angular project. The specific requirement is to display an error message when the value of msisdn is not eligible for renewal. Currently, the hardcoded error message ...

The performance of web API calls on an Angular 7 app deteriorates gradually with each subsequent call

My Angular application in C# is experiencing a slowdown when making calls to the web API and executing a stored procedure. While the C# code performs quickly, the 'Content Download' process is progressively slowing down with each call. https://i ...

How to submit a form in Angular2 without reloading the page

I have a straightforward form to transmit data to my component without refreshing the page. I've tried to override the submit function by using "return false," but it doesn't work as expected, and the page still refreshes. Here is the HTML: ...

The button event listener in React fails to trigger without a page refresh

Within my index.html file, I have included the following code snippet: <head> ... <script type="text/javascript" src="https://mysrc.com/something.js&collectorId=f8n0soi9" </script> <script ...

Create an array with individual key-type pairs for each generic element, then iterate through the array

Consider the enum and type declarations in the code below: enum MyEnum { FIRST, SECOND }; type MyType = { firstKey: string | null, secondKey: boolean, thirdKey: MyEnum } Next, a variable is declared using the type as follows: let glob ...

Jasmine reported that there were no specifications found in the Angular project written in TypeScript

I'm facing a frustrating issue with Karma and Jasmine in my Angular 9 project. Despite setting up the configuration files correctly, I keep getting a "No specs found" message when running ng test. I have tried various adjustments, including creating d ...

Typescript: Implementing the 'types' property in a function returned from React.forwardRef

I'm exploring the option of adding extra properties to the return type of React's forwardRef function. Specifically, I want to include the types property. Although my current implementation is functional, given my limited experience with TypeScri ...

Application: The initialization event in the electron app is not being triggered

I am facing an issue while trying to run my electron app with TypeScript and webpack. I have a main.ts file along with the compiled main.js file. To troubleshoot, I made some edits to the main.js file to verify if the "ready" function is being called. ...

Using React, TypeScript, and Next.js to transform all elements in a static array to their last occurrence

I'm having trouble updating my array. Every time I click the button for the second time, only two or more records are added, similar to the last one I added. Does anyone know how to fix this issue? In the images below, you can see the results of the ...

Angular Tip: How to Trim the Last 4 Characters from a Bound [ngValue] String

I need to connect my [ngValue] property to a string with the last 4 characters removed. What is the most efficient way to do this using ngFor beforehand? Here is the code snippet: <select id="symbolInLineSelector" (change)="insertSymb ...

Error message TS2304: Unable to locate the variable 'title' in vite (vue) + typescript environment

My current project uses Vite (Vue) along with Typescript. However, when I execute the command yarn build (vue-tsc --noEmit && vite build), I encounter a series of errors similar to this one: Error TS2304: Cannot find name 'title'. http ...

Having trouble creating a unit test for exporting to CSV in Angular

Attempting to create a unit test case for the export-to-csv library within an Angular project. Encountering an error where generateCsv is not being called. Despite seeing the code executed in the coverage report, the function is not triggered. Below is the ...

Excluding node modules when not included in tsconfig

Within my Angular project, there is a single tsconfig file that stands alone without extending any other tsconfigs or including any additional properties. Towards the end of the file, we have the following snippet: "angularCompilerOptions": { ...

"Encountered a problem when trying to access properties within a

Struggling to access properties of a nested object in TypeScript while using Angular, I encountered the following error: Object is possibly 'undefined'. Here is the code snippet: export interface Address{ city?: string; neighborhood?: string; } ...

It’s not possible for Typescript to reach an exported function in a different module

Having trouble referencing and using exported methods from another module. I keep getting an error that says 'There is no exported member in SecondModule'. module FirstModule{ export class someClass{ constructor(method: SecondModule ...