Skip to content

Creating a strongly typed Array wrapper duplicates code #12013

Closed
@alfaproject

Description

@alfaproject

TypeScript Version:
Playground

Code

interface IMyArray<T> extends Array<T> {
    first: T;
    reset: () => void;
}

class MyArray<T> extends Array<T> implements IMyArray<T> {
    constructor() {
        super();

        const _arr = [] as MyArray<T>;

        // Property: first
        Object.defineProperty(_arr, 'first', {
            get: () => _arr[0],
            enumerable: true,
            configurable: true
        })

        // Method: reset
        _arr.reset = () => _arr.length = 0;

        return _arr;
    }

    get first(): T { return; }
    reset() { return; }
}

const a = new MyArray<number>();
a.push(...[1, 2, 3]);
alert(a instanceof Array); // true
alert(a.length); // 3
alert(a.first); // 1
a.length = 0;
alert(a.length); // 0
alert(a[0]); // undefined

Expected behavior:
Allow to proper wrap and extend an Array without the custom interface.

Actual behavior:
To create a strongly typed subclassed array, this is the only solution I found, and I think TypeScript can do much better syntax sugar than this.

The default subclassing of an Array doesn't actually create a proper Array, so I don't see the point in that, but my version does despite all of the extra code, so I don't see why it can't be used instead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedA PR has been merged for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions