typescript – 使用ArrayLike声明TypedArray?

我一直在寻找一种在d.ts文件中声明泛型TypedArray类型的方法.由于某些原因,TypedArray似乎不存在但我在某处建议使用ArrayLike< T>.这仍然是最好的解决方案吗?

我可以猜测ArrayLike是什么,但有没有任何文档呢?谷歌搜索和搜索Typescript网站并没有太多.

编辑:我刚刚注意到类型数组构造函数被声明为将ArrayLike作为第一个参数,因此这表明这是正确的方法.

最佳答案 我不确定我是否正确理解您的问题,但以下实例化在TypeScript 1.6(编写本文时的最新稳定版本)中有效:

let t01 = new Uint8Array([1, 2, 3, 4]);
let t02 = new Int8Array([1, 2, 3, 4]);  
let t03 = new Uint8Array([1, 2, 3, 4]);
let t04 = new Uint8ClampedArray([1, 2, 3, 4]);
let t05 = new Int16Array([1, 2, 3, 4]);
let t06 = new Uint16Array([1, 2, 3, 4]);
let t07 = new Int32Array([1, 2, 3, 4]);
let t08 = new Uint32Array([1, 2, 3, 4]);
let t09 = new Float32Array([1.5, 2.5, 3.5, 4.5]);
let t10 = new Float64Array([1.5, 2.5, 3.5, 4.5]);

let arrayBuffer = new ArrayBuffer(16);

(TypeScript playground with the previous script,MDN documentation)

您可以看到类型化数组位于es6.d.ts文件中:

/**
  * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested 
  * number of bytes could not be allocated an exception is raised.
  */
interface Int8Array {
    /** 
      * Returns an array of key, value pairs for every entry in the array
      */
    entries(): IterableIterator<[number, number]>;
    /** 
      * Returns an list of keys in the array
      */
    keys(): IterableIterator<number>;
    /** 
      * Returns an list of values in the array
      */
    values(): IterableIterator<number>;
    [Symbol.iterator](): IterableIterator<number>;
}

这就是你追求的吗?

编辑:

lib.es6.d.ts定义了ArrayLike(参见definition中JavaScript类似于Array的内容):

interface ArrayLike<T> {
    length: number;
    [n: number]: T;
}

Iterable一样

interface Iterable<T> {
    [Symbol.iterator](): Iterator<T>;
}

这是如何定义与您的功能非常相似的功能:

interface Uint8ArrayConstructor {

    //
    // ...
    // 

    /**
      * Creates an array from an array-like or iterable object.
      * @param arrayLike An array-like or iterable object to convert to an array.
      * @param mapfn A mapping function to call on every element of the array.
      * @param thisArg Value of 'this' used to invoke the mapfn.
      */
    from(arrayLike: ArrayLike<number> | Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;
}

所以我将你的功能定义为:

function foo(arrayLike: ArrayLike<number> | Iterable<number>) { ... }
点赞