Search code examples
typescriptunion-types

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);
};

Solution

  • This has worked for me. All credit goes to Marius Schulz - https://blog.mariusschulz.com/2016/08/18/function-overloads-in-typescript#version-4-function-overloads

    function getStyle(styles: ViewStyle[]): ViewStyle;
    function getStyle(styles: TextStyle[]): TextStyle;
    function getStyle(styles: ViewStyle[] | TextStyle[]): ViewStyle | TextStyle {
        return Object.assign({}, ...styles);
    }