值和订单定义对象的数组

时间:2019-07-09 14:13:06

标签: javascript arrays typescript object

使用TypeScript,我想使用订单定义对象创建值数组。

假设以下示例:

  • 是表列headers
  • 订单是这些列中要求的order

类型:

type H = {title: string, description: string};
type O = { [key in keyof H]: number };
const headers: H = {
 description: 'Description',
 title: 'Title',
}
const order: O = {
 title: 0,
 description: 1,
}

(让我们假设order中的值始终被“规范化”为有效的数组索引(它们是从0开始以连续顺序排列的唯一正整数)

我想要以下输出:

['Title', 'Description']

我希望以下方法能起作用:

mapToArray = (headers: H, order: O): string[] => {
    let result: string[] = [];
    for (let k in headers) {
      result[order[k]] = headers[k];
    }

    return result;
  }

但是,出现以下错误:

Type 'H[Extract<keyof H, string>]' is not assignable to type 'string[][O[Extract<keyof H, string>]]'.
  Type 'H' is not assignable to type 'string[]'.
    Type 'H[Extract<keyof H, string>]' is not assignable to type 'string'.
      Type 'H[string]' is not assignable to type 'string'.

有关如何解决此问题的任何建议?预先感谢。

ts编译器选项:

"compilerOptions": {
    "plugins": [
      {
        "name": "tslint-language-service"
      }
    ],
    "target": "es6",
    "lib": [
      "dom",
      "es2015",
      "es2017.object",
      "es2016.array.include"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "skipLibCheck": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": false,
    "outDir": "build",
    "jsx": "preserve",
    "experimentalDecorators": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true,
    "declaration": false,
    "allowJs": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true
  }

2 个答案:

答案 0 :(得分:0)

问题在于,现在,TS编译器假定k循环中的for变量是string

只要让它知道它是H的密钥:

type H = {title: string, description: string};
type O = { [key in keyof H]: number };

const headers: H = {
 description: 'Description',
 title: 'Title',
}

const order: O = {
 title: 0,
 description: 1,
}

const mapToArray = (headers: H, order: O): string[] => {
    let result: string[] = [];
    let k: keyof H;
    for (k in headers) {
      result[order[k]] = headers[k];
    }

    return result;
  }

更新:我还接管了@RezaRahmati的技巧,更正了O的定义,这引发了一个不相关的错误。

See on TS Playground.

答案 1 :(得分:0)

我刚刚创建了一个堆叠闪电战,没问题

https://stackblitz.com/edit/angular-56954561-array-from-values-and-order-definition-object

我所做的唯一更改

type O = { [key in keyof H]: number };