首页 > 解决方案 > 我一直发现自己在使用 TypeScript 时遇到同样的错误。当我需要返回执行后已知的类型时,我该怎么办?

问题描述

例如:这会引发错误

export const toArray = <T>(potentialArr: T): [T] =>
  kindOf(potentialArr) === 'array' ? potentialArr : [potentialArr];

错误

TS2322: Type 'T | [T]' is not assignable to type '[T]'.   Type 'T' is not assignable to type '[T]'.

但我知道这总是会返回一个数组,我做错了什么?TypeScript 忽略了我告诉它它将返回一个数组的事实是没有意义的。

无论我如何在逻辑上撰写此内容,我似乎都无法对打字进行推理。

export const toArray = <T>(potentialArr: T | [T]): T | [T] =>
  kindOf(potentialArr) === 'array' ? potentialArr : [potentialArr];

这应该工作不?

但我得到错误

TS2322: Type 'T | [T | [T]]' is not assignable to type 'T | [T]'.   Type '[T | [T]]' is not assignable to type 'T | [T]'.     Type '[T | [T]]' is not assignable to type '[T]'.       Type 'T | [T]' is not assignable to type 'T'.         'T | [T]' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.           Type '[T]' is not assignable to type 'T'.             '[T]' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.

然后如果我这样做:

export const toArray = <T>(potentialArr: T): T | [T] =>
  kindOf(potentialArr) === 'array' ? potentialArr : [potentialArr];

它可以正常工作,但是从此函数派生的每个值都输入为 x | [x] 这不是真的,因为从这个函数派生的每个值总是 [x]

与此相同:

export const toArray = <T>(potentialArr: T) =>
  kindOf(potentialArr) === 'array' ? potentialArr : [potentialArr];

标签: javascripttypescript

解决方案


这是一个对我来说没有错误的解决方案:

function foo<T>(input: [T] | T): [T] {
  return Array.isArray(input) ? input : [input];
}

如果kindOf不是打字稿理解的东西,您仍然可以以这种方式使用它:

function isArray(input: any): input is any[] {
  return kindOf(input) === 'array';
}

但是您实际上只是重新实现了内置的Array.isArray,这是更正确的方法。


推荐阅读