首页 > 解决方案 > 解构数组时定义类型

问题描述

我想在解构数组时定义类型,但它显示了一些错误:

interface buildTargetProps {
  target: string;
  path: string;
}
interface buildTargets {
  [property: string]: buildTargetProps
};


const ChooseApp: buildTargets = {
  'autocomplete': {
    target: "test",
    path: "./Autocomplete",
  },
  'search': {
    target: "search-root",
    path: "./Search",
  },
};


let [applicationToBuild] = Object.entries(ChooseApp).find(
  ([name, props]: [String, buildTargetProps]) => {
    if (document.getElementById(props.target)) {
      return name;
    }
  }
);

我想要做的是定义“applicationToBuild”变量的类型,因为我已经尝试过:

let [applicationToBuild]: [string] | undefined  = Object.entries(ChooseApp)

我故意跳过了另一个数组元素,因为我不需要它,但是我也尝试添加它,以检查是否可以解决错误,但这也不起作用。

let [applicationToBuild, otherprops]: [string, buildTargetProps] | undefined  = Object.entries(ChooseApp)

但是,这会引发错误。

Type '[string, buildTargetProps] | undefined' is not assignable to type '[string] | undefined'.
  Type '[string, buildTargetProps]' is not assignable to type '[string]'.
    Source has 2 element(s) but target allows only 1.ts(2322)
Type '[string] | undefined' is not an array type.ts(2461)

标签: typescript

解决方案


您正在迭代 JSON 对象的条目。本质上,您正在处理如下所示的元组数组:

[ 
  [ 
    'autocomplete', 
    {
      target: "test",
      path: "./Autocomplete",
    }
  ],
  [
    'search',
    {
      target: "search-root",
      path: "./Search",
    }
  ]
]

.find函数返回与回调函数中提供的条件(返回真值的条件)匹配的第一个对象。因此,它返回 shape 的元组[string, {target: string, path: string}]。但是,如果它不匹配任何东西,它就会返回 undefined。而且,这就是问题所在。如果返回未定义,则解构将不起作用。因此,您返回一个空数组只是为了确保解构正常工作并将值分配给undefined.

这是一个较短的版本:

interface buildTargetProps {
  target: string;
  path: string;
}
interface buildTargets {
  [property: string]: buildTargetProps
};


const ChooseApp: buildTargets = {
  'autocomplete': {
    target: "test",
    path: "./Autocomplete",
  },
  'search': {
    target: "search-root",
    path: "./Search",
  },
};


let [applicationToBuild] = Object
  .entries(ChooseApp)
  .find(
    ([_, props]) => !!document.getElementById(props.target)
  ) || 
  [];

console.log(applicationToBuild)

TS游乐场


推荐阅读