Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the deep meaning of ArrayBufferLike's typescript definition

Tags:

typescript

What's the meaning of the typescript definition for ArrayBufferLike?

interface ArrayBufferTypes {
    ArrayBuffer: ArrayBuffer;
}
type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];

According to my understanding, keyof ArrayBufferTypes is a union type of ArrayBufferTypes's property. so,

type Properties = keyof ArrayBufferTypes; // 'ArrayBuffer'

thereby ArrayBufferLike is obviously equal to ArrayBuffer.

But there must be some differences, otherwise the ArrayBufferLike would be defined as type ArrayBufferLike = ArrayBuffer.

Anyone can help to explain this definition?

like image 912
Leon Avatar asked Sep 20 '18 01:09

Leon


1 Answers

The reason is to allow ArrayBufferTypes to be extended using declaration merging.

This single-member interface is defined in lib.es5.d.ts

interface ArrayBufferTypes {
    ArrayBuffer: ArrayBuffer;
}

But the interface with the same name, but having another member, is defined in es2017.sharedmemory.d.ts

interface ArrayBufferTypes {
    SharedArrayBuffer: SharedArrayBuffer;
}

When both type declarations are included in the program, declarations will be merged and the resulting union type

type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes];

will have two members now: ArrayBuffer and SharedArrayBuffer.

like image 146
artem Avatar answered Oct 20 '22 14:10

artem