gpt4 book ai didi

javascript - TypeScript:TypedArray 的泛型类型定义

转载 作者:数据小太阳 更新时间:2023-10-29 05:53:57 27 4
gpt4 key购买 nike

我正在尝试编写一个函数,通过将任意 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_ELEMENTslice , 和 2) Cannot use 'new' with an expression whose type lacks a call or construct signature对于声明 new source.constructor() .

有没有办法为 TSC 理解我的意图的此类函数指定类型接口(interface)?

对于 1),我理解 ArrayLike 没有为 TypedArray 定义的接口(interface),但单个类型化数组似乎没有从公共(public)类继承...例如,我可以使用 const expand = (source: <Uint32Array|Uint16Array|...>): <Uint32Array|Uint16Array|...> => {} 而不是使用泛型。 .但是它失去了返回类型与源数组相同类型的上下文。

对于 2) 我对如何解决这个错误一无所知。 TSC 提示 source 的构造函数缺少类型信息似乎是合理的。但是,如果我可以为 1) 传递正确的类型,我认为 2) 也会消失。

引用)https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray

最佳答案

这不是很漂亮,但是很有效:

type TypedArray = ArrayLike<any> & {
BYTES_PER_ELEMENT: number;
set(array: ArrayLike<number>, offset?: number): void;
slice(start?: number, end?: number): TypedArray;
};
type TypedArrayConstructor<T> = {
new (): T;
new (size: number): T;
new (buffer: ArrayBuffer): T;
BYTES_PER_ELEMENT: number;
}

export const resize = <T extends TypedArray>(source: T, newSize: number): T => {
if (!source.length) {
return new (source.constructor as TypedArrayConstructor<T>)();
}

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 as TypedArrayConstructor<T>)(buf);
arr.set(source);
return arr;
}
return source.slice(0, newSize) as T;
};

( code in playground )

关于javascript - TypeScript:TypedArray 的泛型类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43988311/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com