1

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?

0

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.