简体   繁体   English

Typescript 将 JS 数组视为 object

[英]Typescript treat JS array as object

I have a js function that outputs an array with 3 numbers.我有一个 js function 输出一个包含 3 个数字的数组。 Could I define a type/interface/whatever that will treat the array as an object.我能否定义一个类型/接口/将数组视为 object 的任何内容。

So that Somethig.GetVector().X transpiles into Something.GetVector()[0]这样Somethig.GetVector().X转译成Something.GetVector()[0]

No, TypeScript transpilation doesn't work that way.不,TypeScript 转译不能那样工作。

You can define a TypeScript interface that extends an array:可以定义扩展数组的 TypeScript 接口:

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.然而,类型信息转变成一无所有——它只被 TypeScript 使用,而不是 JavaScript。

Alternatively, you can define a function that converts the array into an object with friendly property names.或者,您可以定义一个 function 将数组转换为具有友好属性名称的 object。 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" }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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