Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

typescript - How to change the return type from Array.prototype.reduce?

I have an array of objects of type CustomObject, the objects have a field called stringArray that always has an array of strings.

I want to do something like this

const testArray = arrayOfObjects.reduce( (a,b) => {
   return a.stringArray.concat(b.stringArray);
});

The typescript compile complains that the return type is string[] whereas the actual return type should be of type CustomObject. Is there a way to force typescript to realise I am not trying to return CustomObject and instead want my new const testArray to be of string[] type?

I have tried const testArray: string[] = ... but this does not work.

question from:https://stackoverflow.com/questions/65901527/how-to-change-the-return-type-from-array-prototype-reduce

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One of your mistakes is that you want the return of the reduce to be equals to string[], but at the same time you are trying to use a as a.stringArray.

Look at the following playground.

type ObjectDefinition = {
   stringArray: string[];
};

type ArrayOfObject = ObjectDefinition[];

const arrayOfObjects: ArrayOfObject = [{
  stringArray: ['foo'],
}, {
  stringArray: ['bar', 'dog', 'cat'],
}];

const testArray: string[] = arrayOfObjects.reduce((a: string[], b: ObjectDefinition) => {
   return a.concat(b.stringArray);
}, []);

console.log(testArray);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...