typescript - 解构数组时定义类型
问题描述
我想在解构数组时定义类型,但它显示了一些错误:
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)
解决方案
您正在迭代 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)
推荐阅读
- python - 如果我打开两个 GUI 运行 python 项目,每个的速度会比单独运行它们慢吗?
- reactjs - Mysql 5.7 每次都拉
- java - 参考行为
- python - Pandas:通过提供标题名称来阅读列
- sql-server - 多个 INNER JOIN SELECT 查询不返回数据
- jquery - 如果孩子为空,则隐藏父跨度
- c - 如何在 ARM Assembly 中为后缀函数添加中缀
- c# - Entity Framework Core 迁移是否会影响 SQL Server 索引?
- php - 使用 php-fpm 在 nginx 中运行多个项目,为从一个应用程序到另一个应用程序的每个 http 请求创建会话
- android - 如何根据外部条件对recycerview的项目进行排序