0

I'm using typescript and I want to have a type that has a property that is an array. but I want to make the array fixed length, is that possible?

what I mean is :

//example code , not my actual case but similar
export type Car = {
  doors:Door[];//here I want it to be exactly 4 doors
  /// rest of code
}

I tried doing this :

export type Pattern = {
  doors: Array<Door>[4];
  ////
};

but that made doors (property) doors: Door instead of an array of 4 Door objects.

any ideas?

Ataa Aub
  • 127
  • 15

1 Answers1

2

In both Javascript and typescript you can create a fix size Array using new keyword.

Like this:

  let arr: number[] = new Array(3);

But, in your situation you can use tuple type to do this.

Example

export type Car = {
  doors: [Door, Door, Door, Door];
};

// Usage
let car: Car = {
  doors: [
    // fill array
  ]
};

Javascript Example

const arr = new Array (3);

arr [0] = 'door1'
arr [1] = 'door2'
arr [2] = 'door3'

console.log (arr.length)
zain ul din
  • 1
  • 1
  • 2
  • 23