#Class with ReadonlyArray instances

9 messages · Page 1 of 1 (latest)

stark grail
#

Is it possible to define a class that inherits from Array but has ReadonlyArray-typed instances? I tried inheriting from a value that mimics ArrayConstructor but constructs ReadonlyArray-s, however, it doesn't work because "Base constructors must all have the same return type"

const readonlyArray = Array as ArrayConstructor & {
    new <t>(arrayLength?: number): readonly t[]
    new <t>(arrayLength: number): readonly t[]
    new <t>(...items: readonly t[]): readonly t[]
    (arrayLength?: number): readonly any[]
    <t>(arrayLength: number): readonly t[]
    <t>(...items: t[]): readonly t[]
}

export class RangeArray<t> extends readonlyArray<t> {
  // ...
}

Thanks in advance!

proper sigilBOT
#

@stark grail Here's a shortened URL of your playground link! You can remove the full link from your message.

krulod#0

Preview:ts const readonlyArray = Array as ArrayConstructor & { new <t>(arrayLength?: number): readonly t[] new <t>(arrayLength: number): readonly t[] new <t>(...items: readonly t[]): readonly t[] (arrayLength?: number): readonly any[] <t>(arrayLength: number): readonly t[] ...

stark grail
#

ReadonlyArray as class

stark grail
#

Well, it turned out to be too simple, I guess

#

Class with ReadonlyArray instances

bronze iris
#

You mean that you want a constructable ReadonlyArray?

#

yes that's possible.

#

let me make an example

bronze iris
#
// Create a copy of the Array constructor that does not force us to inherit
// push/pop/etc. But the methods still exist at runtime.
const ReadonlyArray = Array as new <T>(...args: T[]) => ReadonlyArray<T>;

class SealedArray<T> extends ReadonlyArray<T> {
  static {
    // Delete methods that cause mutation
    Object.defineProperties(this.prototype, 
      {
        pop: {},
        push: {},
        unshift: {},
        shift: {},
        reverse: {},
        sort: {},
        splice: {},
        fill: {},
        copyWithin: {},
      } satisfies { [P in Exclude<keyof Array<1>, keyof ReadonlyArray<1>>]: {} }
    )
  }
}