Javascript 处理在Typescript中返回对象文字的函数
我目前正在练习打字,遇到了以下问题: (一) 为了达到这个效果, 我考虑了以下选项,但我认为这些都不能保证类型安全Javascript 处理在Typescript中返回对象文字的函数,javascript,typescript,Javascript,Typescript,我目前正在练习打字,遇到了以下问题: (一) 为了达到这个效果, 我考虑了以下选项,但我认为这些都不能保证类型安全 (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 a
(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}
请告知。您可以让函数返回
{[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;
}
必须指定对象的返回类型。因此,我在这里将其制作成一个
Person
界面,您可以将其指定为返回类型。但这并不能解决typechecker不知道您在函数中创建的对象的类型的问题。要解决此问题,请指定在函数中创建的对象也是人
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;
};
const transformFirstAndLast = (arr: string[]): { [key: string]: string } => {
const result = {};
if (!arr.length) {
return result;
}
result[arr[0]] = arr[arr.length - 1];
return result;
}
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;
};