Return type same as input type in TypeScript

2019-07-19 23:47发布

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

3条回答
成全新的幸福
2楼-- · 2019-07-20 00:16

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);
}
查看更多
放荡不羁爱自由
3楼-- · 2019-07-20 00:20

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

查看更多
别忘想泡老子
4楼-- · 2019-07-20 00:29

You can do this:

const flattenObjectsToSingle = <T>(items: T[]): T => { ...
查看更多
登录 后发表回答