NSjonas
NSjonas

Reputation: 12032

How to type object when returning without assignment

I can't seem to figure out how to type an object when it's being returned without assignment.

Example:

interface Foo{
  a: string;
}

const arr = ['a','b','c'];

arr.map(item => {
  return { a: item }; //I want type safety on Foo here
});

// Don't want to have to do this
arr.map(item => {
  let ret: Foo = { a: item }; //first assign
  return ret;
});

I would expect something like return :Foo { a: item }; to work but it doesn't. I don't want to use return { a: item } as Foo; because it isn't typesafe.

Upvotes: 1

Views: 87

Answers (2)

Estus Flask
Estus Flask

Reputation: 222319

This is what generics are usually used for. If a method was typed as generic (Array methods were), optional generic parameter can be passed to provide additional type information.

This generic parameter is there exactly to specify callback return type:

map

It should be:

arr.map<Foo>(item => {
  return { a: item };
});

Upvotes: 2

jcalz
jcalz

Reputation: 327734

You could annotate the return type of the arrow function:

arr.map((item): Foo => {
  return { a: item }; 
});

It's similar to something like

arr.map(function f(item): Foo {
  return { a: item }; 
});

which uses regular function notation, or the more obvious:

function mapper(item: string): Foo {
  return {a: item};
}
arr.map(mapper);

Well, except in both arrow functions, the type of item is inferred from context to be string. In the standalone function you need to specify string explicitly. But in all the examples, the return type is specified as Foo and is type safe.

Does that help?

Upvotes: 3

Related Questions