我目前正在练习打字稿,遇到以下问题:
(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"])
);
请指教。
您必须指定对象的返回类型。所以在这里,我将其设置为一个Person
接口,您可以将其指定为返回类型。但这不能解决类型检查器的问题,因为它不知道obj
您在函数中创建的类型。要解决此问题,您可以指定在函数中创建的对象也是Person
。
interface Person { [key: string]: string }
const transformFirstAndLast = (arr: string[]):Person => {
let obj = {} as Person;
if (!arr.length) return obj;
obj[arr[0]] = arr[arr.length - 1];
return obj;
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句