Return type same as input type in TypeScript

2019-07-19 23:52发布

问题:

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

回答1:

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


回答2:

You can do this:

const flattenObjectsToSingle = <T>(items: T[]): T => { ...


回答3:

If I understand you correctly....

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

see http://www.typescriptlang.org/docs/handbook/advanced-types.html for more cool stuff