Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type same as input type in TypeScript

I have two functions that do the same thing with the only difference that the input types and return types are different. I was wondering how I could "merge" these functions into one and one of the ideas was to use a union type but my constrain is that when the input is one member of the union the returned value has to be the same.

const getViewStyle = (styles: ViewStyle[]): ViewStyle => {
  return Object.assign({}, ...styles);
};

const getTextStyle = (styles: TextStyle[]): TextStyle => {
  return Object.assign({}, ...styles);
};
like image 377
Nick Dima Avatar asked Mar 29 '18 20:03

Nick Dima


People also ask

What is return type in TypeScript?

To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.

How do I return different data types in TypeScript?

Use a union type to define a function with multiple return types in TypeScript, e.g. function getValue(num: number): string | number {} . The function must return a value that is represented in the union type, otherwise the type checker throws an error.

What is the default return type of a function in TypeScript?

The function's return type is string.

How do you define return type?

In computer programming, the return type (or result type) defines and constrains the data type of the value returned from a subroutine or method. In many programming languages (especially statically-typed programming languages such as C, C++, Java) the return type must be explicitly specified when declaring a function.


Video Answer


2 Answers

You can do this:

const flattenObjectsToSingle = <T>(items: T[]): T => { ...
like image 195
Ryan Cavanaugh Avatar answered Sep 23 '22 23:09

Ryan Cavanaugh


A mix of generics and inferred types would be the best. The accepted answer would let the linter of typescript keep complaining if you expect one of the types to be returned when you are using the function.

So, in my opinion, this would be the best answer:

const getStyle = <T extends TextStyle | ViewStyle >(styles: T[]): T => { 
      return Object.assign({}, ...styles);
};

What this basicly say is that The function expect an array of TextStyle or ViewStyle and return one record of what ever type is given.

Credit goes to Ben Awad video on YouTube: https://www.youtube.com/watch?v=nViEqpgwxHE

like image 35
Husein.Kasem Avatar answered Sep 22 '22 23:09

Husein.Kasem