javascript - 处理在 Typescript 中返回对象字面量的函数
问题描述
我目前正在练习打字稿并遇到以下问题:
(1)
transformFirstAndLast : needs to return object where key equals to
array[0] && value equals to array[length-1]
//EX1
let arr = ['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce']; // Expected Input
let output = transformFirstAndLast(arr); //
console.log(output); // --> { Queen : 'Beyonce' } // Expected Output
//EX2
arr = ['Kevin', 'Bacon', 'Love', 'Hart', 'Costner', 'Spacey'];
output = transformFirstAndLast(arr);
console.log(output); // --> { Kevin : 'Spacey' }
为了达到效果,
我考虑了以下选项,但我认为这些都不能确保类型安全。
(Question1)
// TRY 1 : {} // does not work
// TRY 2 : <T>
// TRY 3 : object -> this works, but wouldn't this indicate anything other than primitive?
// TRY 4 : type -> I cant assign something like type foo { array[0]: string, array[length-1]: string}
我目前的解决方案:
const transformFirstAndLast = (arr: string[]):object => {
let obj = {};
if (!arr.length) return obj;
obj[arr[0]] = arr[arr.length - 1]; // (Question2) Also why is this not working????
//error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Object'. No index signature with a parameter of type 'string' was found on type 'Object'.ts(7053)
return obj;
};
console.log(
transformFirstAndLast(["Queen", "Elizabeth", "Of Hearts", "Beyonce"])
);
请指教。
解决方案
你可以让你的函数返回{ [key: string]: string }
,像这样:
const transformFirstAndLast = (arr: string[]): { [key: string]: string } => {
const result = {};
if (!arr.length) {
return result;
}
result[arr[0]] = arr[arr.length - 1];
return result;
}
推荐阅读
- flutter - 颤振小部件的最佳定义?
- r - 行和列中有多个项目的交叉表
- python - 对加权散点图使用颜色强度而不是气泡大小
- timezone-offset - 计算仅知道当前偏移量的未来日期的时区偏移量
- php - 数据库异常在 Mac / Unix 系统上从 PHP 连接到 MSSQL 数据库时找不到驱动程序
- javascript - 如何为渲染和逻辑重构反应组件?
- javascript - 反应数组中的子组件 - 将元素移动到其他索引时出现问题
- latex - LaTeXt PDF文件打不开
- reactjs - React-leaflet v3.1.0 中的搜索框实现给出错误“TypeError: Object(...) is not a function”
- python - 获取两个 geopandas 数据框几何点之间的距离