Home > OS >  How do I type a array that has a mix of number and object (named array)
How do I type a array that has a mix of number and object (named array)

Time:08-11

I have this sample code:

const arr = [320, 480, 1024];
arr.small = arr[0];
arr.medium = arr[1];
arr.large = arr[2];

console.log(arr) will output:

[320, 480, 1024, small: 320, medium: 480, large: 1024]

What would be the type (interface on typescript) of arr?

note: It might seem weird, but it's common on a design system theme file, where you want support by scale or by naming.

CodePudding user response:

You can extend Array:

interface MyArr<T> extends Array<T> {
  small?: T
  medium?: T
  large?: T
}

const arr: MyArr<number> = [320, 480, 1024];
arr.small = arr[0];
arr.medium = arr[1];
arr.large = arr[2];

Playground link

I assume you could make the properties required if you need to, in which case you probably would create a normal array first and then extend it with the additional properties via Object.assign:

interface MyArr<T> extends Array<T> {
  small: T
  medium: T
  large: T
}

const arr = [320, 480, 1024];

const extendedArray: MyArr<number> = Object.assign([...arr], {
  small: arr[0],
  medium: arr[1],
  large: arr[2],
})

Alternatively if you don't actually need access to array methods, you can create an object with an index signature:

interface MyObj<T> {
  [index: number]: T
  small: T
  medium: T
  large: T
}

CodePudding user response:

The best type description of this array would be like this

type element = number | Object
type mixArray = element[]
type Two = {twoId:number, value:string}

const oneItem:mixArray = [320, 480, 1024, {small: 320}, {medium: 480}, {large: 1024}]

You can add more specificity to the Object and it would be like this

type elaborateElem = number | {small?: number, medium?: number, large?: number}
type elaborateMixArray = elaborateElem[]

const arr2:elaborateMixArray = [320, 480, 1024, {small: 320}, {medium: 480}, {large: 1024}]

Play ground link

I would really recommend using Zod in your typescript to help in organizing such issues and to help you in type managment

  • Related