Home > Software design >  How to specify return type for TypeScript anonymous inline arrow function
How to specify return type for TypeScript anonymous inline arrow function

Time:11-21

There is this question and answer which helps give a concise way to define the shape of a NAMED arrow function, but does not touch on anonymous inline functions: Specify return type in TypeScript arrow function

I would like to map one object type to another object type using a simple inline anonymous arrow function:

type MyType = {
    foo: string
};
type OtherType = {
    bar: string
};

const myTypeArr: MyType[] = [{foo: 'abc'}, {foo: 'qwe'}];

// note the anonymous inline arrow function below
const otherTypeArr: OtherType[] = myTypeArr.map(o => ({bar: o.foo}));

The compiler seems to accept this as valid code. And throws errors if I do something like this:

// Error: Property 'baz' does not exist on type 'MyType'.
const otherTypeArr: OtherType[] = myTypeArr.map(o => ({bar: o.baz}));
// Error: Property 'bar' is missing in type '{ baz: string; }' but required in type 'OtherType'
const otherTypeArr: OtherType[] = myTypeArr.map(o => ({baz: o.foo}));

But I believe it is inferring the types in the anonymous function. Is there a way to specify the input types and return types explicitly?

I think I can specify the input type easily like this:

const otherTypeArr: OtherType[] = myTypeArr.map((o: MyType) => ({bar: o.foo}));

But I still don't see a way to manually specify the return type on the function. Is the fact that I already specify OtherType[] in the variable the only way?

CodePudding user response:

You can provide a generic type argument to array.map<T>(), like this:

TS Playground link

// variable is annotated
const otherTypeArr1: OtherType[] = myTypeArr.map(o => ({bar: o.foo}));

// return type of callback function is specified in generic type arguent to array.map
const otherTypeArr2 = myTypeArr.map<OtherType>(o => ({bar: o.foo}));

CodePudding user response:

The solution in the answer to the other question works here too. Even anonymous arrow functions allow you to annotate the return type with a colon after the parameter list's closing parenthesis and before the arrow, like this:

(o: MyType): OtherType => ({ bar: o.foo })
//         ^^^^^^^^^^^ <-- return type annotation

And you can verify that this works as desired:

const otherTypeArr =
    myTypeArr.map((o: MyType): OtherType => ({ bar: o.foo }));

// const otherTypeArr: OtherType[]

Playground link to code

  • Related