Home > Software engineering >  What is best way to assign the type of an array that has properties using typescript?
What is best way to assign the type of an array that has properties using typescript?

Time:05-20

Here is my type of interest - an array with properties.


type MyArray = string[];

interface MyArrayWithProperties extends MyArray {
    someProperty: boolean
  }

This is the only way I've been able to assign the type.


let arr : any = ['a','b', 'c']; //must declare array as any

arr.someProperty = true //then add the property

const arrWProps = arr as MyArrayWithProperties; //then cast as type

Is a better way? Usually I don't need to build variables in steps as any before setting the real type.

CodePudding user response:

Object.assign can be used to create an array literal and assign a value to it all at once before finally putting it into the variable on the left (with the right type).

const arr: MyArrayWithProperties = Object.assign(['a','b', 'c'], { someProperty: true });

That said, I'd usually recommend not putting arbitrary key-value pairs onto arrays like this - programmers will generally expect an array to contain only properties that arrays usually have (numeric indicies, .length, and array methods). There aren't any rules against it, but you might consider if there are other ways you might structure the code to get the same effect.

  • Related