简体   繁体   English

出现 Typescript 错误:类型“any[]”不可分配给类型“never[]”。 TS2345

[英]Getting Typescript error: Type 'any[]' is not assignable to type 'never[]'. TS2345

I'm not sure why I'm getting this error.我不确定为什么会收到此错误。 Type 'any[]' is not assignable to type 'never[]'. TS2345 Type 'any[]' is not assignable to type 'never[]'. TS2345 Here is my code. Type 'any[]' is not assignable to type 'never[]'. TS2345这是我的代码。 It's complaining about the merged array.它抱怨合并的数组。

  const [allInfo, setAllInfo] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const validatorResponse = await axios.get(validatorEndpoint);
      const validatorIps = [];
      for (let i = 0; i < validatorResponse.data.count; i += 1) {
        const ipAddress = validatorResponse.data.results[i].ip_address;
        validatorIps.push({query: ipAddress});
      }
      const resultBatch = await axios.post(ipInfoEndpoint, validatorIps);
      const merged = [];
      for (let i = 0; i < validatorResponse.data.results.length; i += 1) {
        merged.push({
          ...validatorResponse.data.results[i],
          ...resultBatch.data[i],
        });
      }
      console.log(merged);
      setAllInfo(merged);
    }
    fetchData();
  }, []);

This is the line returning the error -这是返回错误的行 -

setAllInfo(merged);

I've tried我试过了

const result : string[] = [];

As well as const和常量一样

[allInfo, setAllInfo] = useState([] as any);

Giving your state an interface to strictly type it is a common pattern when using Typescript and React, otherwise the Typescript compiler will infer it.在使用 Typescript 和 React 时,为您的 state 提供一个接口来严格键入它是一种常见模式,否则 Typescript 编译器会推断它。 While with many other types inference will work, with an array most of the time it won't because the safest type to assume for an empty array is never[] .虽然对于许多其他类型的推断将起作用,但对于数组大多数时候它不会,因为假设空数组的最安全类型是never[]

All of that to say that when you are creating an array that is assigned to a variable it is best to type that array strictly using an interface or custom type.综上所述,当您创建一个分配给变量的数组时,最好严格使用接口或自定义类型来键入该数组。

https://www.typescriptlang.org/docs/handbook/interfaces.htmlhttps://www.typescriptlang.org/docs/handbook/interfaces.html

So your code will often look more like this:所以你的代码通常看起来更像这样:

interface Foo {
  ...
}
...

const [allInfo, setAllInfo] = useState<Foo[]>([]);

const fetchData = async (): Promise<void> => {
  const { 
    data: {
     results = []
    } = {} 
  } = await axios.get(validatorEndpoint);
  const validatorIps = results.map(({ ip_address }) => ({query: id_address}));
  const { data = [] } = await axios.post(ipInfoEndpoint, validatorIps);

  const merged = results.map((result, i) => ({
    ...result,
    ...data[i]
  });

 setAllInfo(merged)
}

useEffect(() => {
  fetchData();
}, []);

I typed that using what information I had, but in the future you should also give types to your API responses inside of fetchData or you'll run into more type issues by relying on inference.我使用我所拥有的信息输入了该信息,但将来您还应该在 fetchData 中为您的fetchData响应提供类型,否则您将依靠推理遇到更多类型问题。

One last thing, fetchData inside of the useEffect is violating exhaustive-deps linter rule React has.最后一件事, fetchData中的useEffect违反了 React 的exhaustive-deps linter 规则。 It isn't hugely problematic in this case, but fetchData should really be defined inside the useEffect or with the useCallback hook.在这种情况下问题不大,但fetchData确实应该在useEffectuseCallback挂钩中定义。

You can fix the error be giving merged a better type than the inferred one ( never[] ).您可以通过为merged提供比推断出的类型更好的类型( never[] )来修复错误。

const merged: any[] = []; should be enough, but I would recommend you consider a better type.应该足够了,但我建议你考虑一个更好的类型。

You can also help typescript infer the type by using the Array.prototype.map method, and it's generally better to use .map when you want to create new array with every element transformed from the original array.您还可以使用Array.prototype.map方法帮助 typescript 推断类型,当您想使用原始数组的每个转换后的元素创建新数组时,通常最好使用.map方法。

const merged = validatorResponse.data.results.map((result, i) => ({
   ...result,
   ...resultBatch.data[i],
})

use default values this prevent future TypeError, try to use real typed, not use any like type使用默认值以防止将来出现 TypeError,尝试使用真正的类型,不要使用任何类似的类型

const [allInfo, setAllInfo] = useState<Array<typed>>([]);

const fetchData = async (): Promise<void> => {
  const { 
    data: {
     results = []
    } = {} 
  } = await axios.get(validatorEndpoint);
  const validatorIps = results.map(({ ip_address}) => ({query: id_address}));

  const { data = []}= await axios.post(ipInfoEndpoint, validatorIps);
  const merged = results.map((result, i) => ({
    ...result,
    ...data[i]
  });
 setAllInfo(merged)
}

useEffect(() => {
  fetchData();
}, []);

` `

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular2 / TypeScript:错误TS2345:类型'String'的参数不能分配给'string'类型的参数 - Angular2/TypeScript: error TS2345: Argument of type 'String' is not assignable to parameter of type 'string' 人员类型的 TypeScript 错误 (TS2345) 参数 | undefined 不能分配给 Person 类型的参数 - TypeScript Error (TS2345) argument of type Person | undefined is not assignable to paramater of type Person typescript:类型&#39;any []&#39;的参数不能分配给&#39;[]&#39;类型的参数.ts(2345) - typescript : Argument of type 'any[]' is not assignable to parameter of type '[]'.ts(2345) TS2345:“事件”类型的参数不可分配给“HtmlInputEvent”类型的参数 - TS2345: Argument of type 'Event' is not assignable to parameter of type 'HtmlInputEvent' Ngrx/effects:获取错误 TS2345:“Product[]”类型的参数不可分配给“Product”类型的参数 - Ngrx/effects: get error TS2345: Argument of type 'Product[]' is not assignable to parameter of type 'Product' 错误 TS2345:“事件”类型的参数不可分配给“{目标:{值:字符串; }; }' - error TS2345: Argument of type 'Event' is not assignable to parameter of type '{ target: { value: string; }; }' 错误TS2345:类型为&#39;(a:Test,b:Test)=&gt;布尔| 1&#39;不能分配给类型&#39;(a:Test,b:Test)=&gt; number&#39;的参数 - error TS2345: Argument of type '(a: Test, b: Test) => boolean | 1' is not assignable to parameter of type '(a: Test, b: Test) => number' TS2345:“日期”类型的参数 | null' 不可分配给类型为“string |”的参数日期 | 不明确的' - TS2345: Argument of type 'Date | null' is not assignable to parameter of type 'string | Date | undefined' TS2345:“可观察”类型的参数<todointerface[]> ' 不能分配给 'TodoInterface[]' 类型的参数</todointerface[]> - TS2345: Argument of type 'Observable<TodoInterface[]>' is not assignable to parameter of type 'TodoInterface[]' 使用TypeScript 2.0-&gt; TS2345在React中处理多个输入:类型&#39;{[x:string]:string | 布尔; }” - Handing multiple inputs in React with TypeScript 2.0 -> TS2345: Argument of type '{ [x: string]: string | boolean; }'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM