简体   繁体   中英

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]

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" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM