处理在Typescript中返回对象文字的函数

paul.kim1901

我目前正在练习打字稿,遇到以下问题:

(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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

从异步函数销毁的对象中的类型在Typescript中返回

Typescript箭头函数中的对象文字参数声明如何工作?

处理 TypeScript 中的任意对象

根据Typescript中输入对象的属性使用键从函数返回对象

使用TypeScript函数返回JSON对象

嵌套对象中的函数返回

Typescript:当类中存在函数时,无法使用对象文字实例化对象

什么是 TypeScript 中的“对象文字”?

在多处理/映射函数中返回计数器对象

如何处理在Scala中返回具有泛型类型的对象的函数

传播对象文字函数参数并返回简写

firebase 云函数从批处理函数返回 json 对象

从TypeScript中的函数返回对象(具有特定键,值类型)

javascript/HTML:将事件处理函数与对象作为 HTML 字符串文字中的参数绑定

在TypeScript中的异步函数中返回Promise

Typescript:确保对象文字扩展接口,但返回实际对象类型

处理R中xts对象的apply函数

如何使用Angular2中的Observable Map函数将Http服务返回的Response对象映射到TypeScript对象

VueJS:使用对象文字与返回对象的函数定义“数据”

TypeScript中对象文字中的类型定义

在TypeScript中动态返回类构造函数

在 TypeScript 函数中输入返回的匿名类

在AJAX函数中以JavaScript返回对象

在R函数中返回多个对象

如何使函数返回VBA中的对象列表

如何返回在函数中创建的对象?

如何从 PHP 中的函数返回哈希对象?

Typescript d.ts中的函数对象

使用TypeScript中的属性构建函数对象