在 TypeScript 中获取 TypedArray 的类型

Getting the type of a TypedArray in TypeScript

我正在使用以下代码获取 TypeScript 中 TypedArray 的实际数据类型

type BufferElementType =
    | "float"
    | "uint8"
    | "uint16"
    | "uint32"
    | "int8"
    | "int16"
    | "int32";

function getBufferElementType(buffer: ArrayBufferView): BufferElementType {
    const name = (buffer as any).__proto__.constructor.name;
    switch (name) {
        case "Int8Array":
            return "int8";
        case "Uint8Array":
            return "uint8";
        case "Int16Array":
            return "int16";
        case "Uint16Array":
            return "uint16";
        case "Int32Array":
            return "int32";
        case "Uint32Array":
            return "uint32";
        case "Float32Array":
            return "float";
    }

    throw new Error(`Unsupported buffer type ${name}`);
}

我想知道有没有更好的方法不用(buffer as any).__proto__.constructor.name;

您可以使用 instanceof 而不是 .__proto__.constructor.name; 来检查:

function getBufferElementType(buffer: ArrayBufferView): BufferElementType {
    if (buffer instanceof Int8Array) {
        return "int8";
    } else if (buffer instanceof Uint8Array) {
        return "uint8";
    } // etc...
}

或者,如果检查不应包括子类,您可以直接比较 .constructor

if (buffer.constructor === Int8Array) {