【发布时间】:2017-05-15 20:30:32
【问题描述】:
我正在尝试编写一个函数,该函数通过将任意 TypedArray 作为输入来扩展/缩小 TypedArray,并返回一个具有不同大小的新的相同类型的 TypedArray,并将原始元素复制到其中。
例如,当你通过new Uint32Array([1,2,3]),新大小为5,它会返回new Uint32Array([1,2,3,0,0])。
export const resize = <T>(
source: ArrayLike<T>, newSize: number,
): ArrayLike<T> => {
if (!source.length) { return new source.constructor(newSize); }
newSize = typeof newSize === "number" ? newSize : source.length;
if (newSize >= source.length) {
const buf = new ArrayBuffer(newSize * source.BYTES_PER_ELEMENT);
const arr = new source.constructor(buf);
arr.set(source);
return arr;
}
return source.slice(0, newSize);
};
虽然代码按预期工作,但 TSC 抱怨 1) ArrayType 没有 BYTES_PER_ELEMENT 和 slice,以及 2) Cannot use 'new' with an expression whose type lacks a call or construct signature 声明 new source.constructor()。
有没有办法为 TSC 理解我意图的此类函数指定类型接口?
对于 1),我了解 ArrayLike 没有为 TypedArray 定义接口,但单个类型化数组似乎没有从公共类继承...例如,我可以使用 const expand = (source: <Uint32Array|Uint16Array|...>): <Uint32Array|Uint16Array|...> => {},而不是使用泛型。但它失去了返回类型与源数组相同类型的上下文。
对于 2) 我对如何解决此错误一无所知。 TSC 抱怨源的构造函数缺少类型信息似乎是合理的。但是如果我可以为 1) 传递正确的类型,我认为 2) 也会消失。
参考)https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
【问题讨论】:
标签: javascript generics typescript typed-arrays