首页 > 解决方案 > 处理在 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"])
);

请指教。

标签: javascripttypescript

解决方案


你可以让你的函数返回{ [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;
}

推荐阅读