Chrillewoodz
Chrillewoodz

Reputation: 28338

TypeScript how to define tuple type for an empty array?

What I'm trying to do is convert a const object into a class so that I can create readonly properties for example. This to ensure that the values never changes.

In my class I'm trying to create a module property which should be defined, but always empty.

I tried a number of different things:

public modules: Readonly<[]> = []; // Error: A tuple type element list cannot be empty.
public readonly modules: IModule[] = []; // Disallows re-assignment, but still allows things such as push, pop etc.

interface EmptyTuple {
  length: 0;
}

// Types of property 'length' are incompatible. Type 'number' is not assignable to type '0'.
public modules: Readonly<EmptyTuple> = [];

The latest one doesn't make any sense since 0 is a number... I really have no idea what I'm doing here really so some guidance would be perfect.

I tried looking at https://github.com/Microsoft/TypeScript/issues/13126 to see if I could find some sort of answer but to no avail.

Does anyone know how to achieve having an empty array that cannot be modified?

Upvotes: 0

Views: 15943

Answers (3)

Welyngton Dal Pra
Welyngton Dal Pra

Reputation: 774

You can do things like this to avoid these errors:

    public modules: = any[]; // Error: A tuple type element list cannot be empty.
    public readonly modules: = any[]; // Disallows re-assignment, but still allows things such as push, pop etc.

...

Upvotes: 1

manroe
manroe

Reputation: 1785

TypeScript 3.0 now includes better tuple type support:

type EmptyTuple = []

const empty: EmptyTuple = [] // OK

//  Type '[number]' is not assignable to type '[]'.
//    Types of property 'length' are incompatible.
//      Type '1' is not assignable to type '0'.
const err1: EmptyTuple = [1]

Source - TS 3.0 Announcement

Upvotes: 2

Aleksey L.
Aleksey L.

Reputation: 37986

Does anyone know how to achieve having an empty array that cannot be modified?

You can type the field as ReadonlyArray and mark it with readonly keyword:

class Foo {
  readonly modules: ReadonlyArray<{}> = [];
}

const foo = new Foo();

foo.modules = []; //error
foo.modules.push({}) //error

Upvotes: 3

Related Questions