0

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]

1 Answer 1

3

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