您可以向类型化数组视图构造函数传递数字、JavaScript本机数组或另一种类型(以及其他内容

const a = new Int32Array(3);
const b = new Int32Array([1, 2, 3]);
const c = new Int32Array(new Int32Array([1, 2, 3]));

考虑到这一点,我希望这份Typescript 能奏效

function make(data: number | number[] | Int32Array) {
  return new Int32Array(data);
} 

typescript playground

但失败的原因是

No overload matches this call.
 The last overload gave the following error.
   Argument of type 'number | Int32Array | number[]' is not assignable to parameter of type 'ArrayBufferLike'.
     Type 'number' is not assignable to type 'ArrayBufferLike'.(2769)

我做错什么了吗?这是已知的限制吗?

推荐答案

类型化数组构造函数的类型脚本库类型(如Int32Array构造函数,来自lib.es5.d.tslib.es2015.iterable.d.tslib.es2017.typedarrays.d.ts,每个添加对应于语言规范随时间的变化)被实现为一系列overloads.也就是说,有多个呼叫签名:

interface Int32ArrayConstructor {
  // from lib.es5.d.ts
  new(length: number): Int32Array;
  new(array: ArrayLike<number> | ArrayBufferLike): Int32Array;
  new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array;
  // from lib.es2015.iterable.d.ts
  new(elements: Iterable<number>): Int32Array;
  // from lib.es2017.typedarrays.d.ts
  new(): Int32Array;
}

当您在类型脚本中调用一个重载函数(或new个重载构造函数)时,它恰好解析为one个调用签名.如果没有合适的单个调用签名,则调用失败.类型判断器nottry 合成组合的呼叫签名,该组合的呼叫签名将接受由各个呼叫签名接受的union个参数.对于这种支持,存在一个长期悬而未决的问题,即microsoft/TypeScript#14107.除非这一点发生变化,否则您将需要解决它.


到目前为止,最简单的解决方法是使用type assertion:

return new Int32Array(data as number); // for example

如果你想"修复"Int32Array,你可以使用一个更宽松的调用签名(如果你在一个模块中,而不是在环境作用域中,请记住使用global augmentation):

// declare global { // use this if you are in a module
interface Int32ArrayConstructor {
  new(x?: number | Iterable<number> | ArrayBufferLike): Int32Array;
}
// }

然后,您的原始呼叫将不会出现问题.

Playground link to code

Typescript相关问答推荐

如何从具有给定键列表的对象类型的联合中构造类型

React-Native运行方法通过监听另一个状态来更新一个状态

动态判断TypScript对象是否具有不带自定义类型保护的键

有没有可能使用redux工具包的中间件同时监听状态的变化和操作

如何将所有props传递给React中的组件?

如何调整对象 struct 复杂的脚本函数的泛型类型?

为什么有条件渲染会导致material 自动完成中出现奇怪的动画?

Angular 15使用react 式表单在数组内部创建动态表单数组

使用数组作为类型中允许的键的列表

如何合并两个泛型对象并获得完整的类型安全结果?

如何在使用条件类型时使用void

自定义 Select 组件的类型问题:使用带逗号的泛型类型<;T与不带逗号的<;T&>;时出错

自动通用回调

try 使Angular依赖注入工作

作为函数参数的联合类型的键

map 未显示控制台未显示任何错误@reaction-google-map/api

编剧- Select 动态下拉选项

如何提取具有索引签名的类型中定义的键

为什么 Typescript 无法正确推断数组元素的类型?

有没有办法将类型与关键更改相匹配?