Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

typescript - When refactoring code into separate files, "TS2345: Argument of type is not assignable to parameter of type"

I'm new to TypeScript and I'm refactoring my React app. I got the following error.

TS2345: Argument of type '{ standardHeaders: Headers; }' is not assignable to parameter of type 'RequestInit'.
  Object literal may only specify known properties, and 'standardHeaders' does not exist in type 'RequestInit'.

This is my original code, which works without any TypeScript errors:

  const headers = new Headers({
    Accept: 'application/vnd.api+json',
  });
  fetch(url, { headers })

Then I moved headers to a separate file because it is used in several places:

globals.tsx

export const standardHeaders = new Headers({
  Accept: 'application/vnd.api+json',
});

myfile.tsx

import { standardHeaders } from '../globals';
fetch(url, { standardHeaders })

This causes the "type is not assignable to parameter" error.

I assume I need to set the type of standardHeaders somehow, but how do I do that?

question from:https://stackoverflow.com/questions/65919488/when-refactoring-code-into-separate-files-ts2345-argument-of-type-is-not-assi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The valid 2nd parameter of fetch is an object containing headers instead of standardHeaders so as long as you change the property then it would work:

import { standardHeaders } from '../globals';
fetch(url, { headers: standardHeaders })

Your original code has variable name and property are the same headers that's why it works normally


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...