kayahr
kayahr

Reputation: 22020

How to only accept ArrayBuffer as parameter

I have a class which accepts an array buffer parameter in the constructor like this:

class Test {
    public constructor(buffer: ArrayBuffer) {
        ...
    }
}

Problem is the ArrayBuffer type is a pretty small interface which also accidentally matches typed arrays (which are not array buffers). So my class can also be constructed with a typed array as parameter. So both calls are valid for the compiler:

new Test(new Float32Array([ 1, 2, 3, 4 ]).buffer);  // <-- Correct usage
new Test(new Float32Array([ 1, 2, 3, 4 ]));         // <-- Wrong usage

To prevent using my API in the wrong way I want the compiler to reject passing typed arrays to the constructor. Anyone knows a nice little trick how to achieve this?

Upvotes: 2

Views: 507

Answers (1)

kayahr
kayahr

Reputation: 22020

Nevermind, found a solution:

type StrictArrayBuffer = ArrayBuffer & { buffer?: undefined };

It matches a real ArrayBuffer because it has no buffer property and it doesn't match a typed array because this type has a buffer property which doesn't match the type undefined.

Upvotes: 3

Related Questions