来自值和顺序定义对象的数组



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

假设以下示例:

  • 是表列headers
  • order 是这些列的请求的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
  }

我刚刚创建了一个stackblitz,而没有问题

https://stackblitz.com/edit/angular-56954561-aray-from-values-and-corm-values-and-rord-definition-object

我做出的唯一更改

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

问题是现在,TS编译器假设您的k循环中的CC_4变量是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;
  }

update :我还接管了 @rezarahmati的提示,纠正了O的定义,该定义引发了无关的错误。

请参阅TS游乐场。

最新更新