Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

备稿计划: 为什么 TS 要求 ArrayBuffer 类型, 却允许传入 Uint8Array 类型 #128

Open
iugo opened this issue Jan 29, 2023 · 0 comments

Comments

@iugo
Copy link
Member

iugo commented Jan 29, 2023

// 有一个函数, 要求参数为 ArrayBuffer 类型
function test(v: ArrayBuffer) {
    console.log(v, v instanceof ArrayBuffer);
}
const ab = new ArrayBuffer(4);
test(ab);

const u8 = new Uint8Array([1, 2]);
test(u8); // 要求 ArrayBuffer 类型, 但也允许 Uint8Array 类型?

const u32 = new Uint32Array([1, 2]);
test(u32); // 要求 ArrayBuffer 类型, 但也允许 Uint32Array 类型?

为什么允许, 因为如果传入 Uint8Array, 一定能获取到其 ArrayBuffer.

传入 Uint32Array 也可以, 不只是它们, 所有 TypedArray 都有一个 buffer 属性,
指向一个 ArrayBuffer 类型的数据.

不过 TypedArray 不是一个可以直接使用的对象, 但它真的存在,
比如通过 Object.getPrototypeOf(Uint8Array) 可以看到.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant