EuberDeveloper
EuberDeveloper

Reputation: 1048

Typescript - Class type in generics gives error when trying to instantiate it

Let's say that I have this class:

export abstract class BytesView<T> {
    constructor(protected _buffer: T) {}

    get buffer(): T {
        return this._buffer;
    }
    set buffer(value: T) {
        this._buffer = value;
    }

    abstract get length(): number;
}

which is extended by these two classes:

export class BufferView extends BytesView<Buffer> {
    get length(): number {
        return this._buffer.length;
    }
}

export class ArrayBufferView extends BytesView<ArrayBuffer> {
    get length(): number {
        return this._buffer.byteLength;
    }
}

Now I have this class that uses Generics and tries to use them:

export class MyClass<B, V extends BytesView<B>> {
    private readonly _bytesView: V;

    constructor(buffer: B) {
        this._bytesView = new V(buffer); // I get an error in this line
    }
}

In the line with new V(buffer) I get an error:

'V' only refers to a type, but is being used as a value here.ts (2693)

How can I solve this?

Upvotes: 0

Views: 61

Answers (1)

David Shortman
David Shortman

Reputation: 992

You want to create a new buffer view class that handles a buffer of type B. This is a runtime behavior.

Typescript does not use generic types to compile Javascript that fulfills this use case. You will have to determine the type of the buffer in order to instantiate the appropriate buffer view class.

class MyClass<B> {
    private readonly _bytesView: BytesView<unknown> | undefined;

    constructor(buffer: B) {
      if (buffer instanceof ArrayBuffer) {
        this._bytesView = new ArrayBufferView(buffer);
      } else if (Array.isArray(buffer)) {
        this._bytesView = new BufferView(buffer);
      }
    }
}

Playground

Upvotes: 2

Related Questions