Canopy
Canopy

Reputation: 51

Typescript classes extends Tuple

I'm looking for a way to extend a Tuple in TypeScript.

In C#, you can easily do:

public class extends String { ... }

In TypeScript, I would like to be able to write something like this:

export class Field extends [string, string] { ... }

Any ideas ?

Note: My goal is naming each tuple member.

Upvotes: 2

Views: 1607

Answers (2)

NSjonas
NSjonas

Reputation: 12032

If you goal is just to name the tuples...

With typescript > 4.0 (in Beta at time of writing this), you can now name tuples:

type MyNamedTuple = [foo: string, bar: string];

This is helpful to get code complete when using ...args with tuple generics

enter image description here

Upvotes: 2

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249586

If you need to name your tuple members you might be better off with an interface.

If you really want to derive the tuple, you can do it, but you will need a tuple constructor to act as the base class. Tuples at runtime are just arrays in javascript so what we really want is typed alias for the Array constructor, so your are really inheriting Array:

const tupleConstructor: new (...p: [string, string]) => [string, string] = Array as any;
class Field extends tupleConstructor{ 
  constructor(...p: [string, string]) {
    super(...p);
    (this as any).__proto__ = Field.prototype; // fix for inheriting arrays
  }
  get firstName() { return this[0]; }
  get lastName() { return this[1];}
}

let a = new Field("1", "1");
let [a0, a1] = a;
console.log(`0: ${a0}`);
console.log(`1: ${a1}`);

let { firstName, lastName} = a;
console.log(`firstName: ${firstName}`);
console.log(`lastName: ${lastName}`);

Upvotes: 4

Related Questions