Search code examples
typescripttypescript-definitions

Typescript treat JS array as object


I have a js function that outputs an array with 3 numbers. Could I define a type/interface/whatever that will treat the array as an object.

So that Somethig.GetVector().X transpiles into Something.GetVector()[0]


Solution

  • No, TypeScript transpilation doesn't work that way.

    You can define a TypeScript interface that extends an array:

    interface ExtArr extends Array<string> {
      extProp?: string
    }
    
    const a: ExtArr = ['foo', 'bar', 'baz']
    a.extProp = 'quux'
    

    However, the type information transpiles away to nothing - it's only used by TypeScript, not JavaScript.

    Alternatively, you can define a function that converts the array into an object with friendly property names. It sounds like this is probably what you want for your use case:

    const makeFriendly = (unfriendlyArray: string[] /* or whatever type */) => {
      const [ propName1, propName2, propName3 ] = unfriendlyArray
    
      return { propName1, propName2, propName3 }
    }
    
    makeFriendly(['foo', 'bar', 'baz']) // { propName1: "foo", propName2: "bar", propName3: "baz" }