2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.