返回类型与TypeScript中的输入类型相同 [英] Return type same as input type in TypeScript

查看:123
本文介绍了返回类型与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);
};

推荐答案

这对我有用.所有功劳归Marius Schulz- https://blog.mariusschulz.com/2016/08/18/function-overloads-in-typescript#version-4-function-overloads

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

这篇关于返回类型与TypeScript中的输入类型相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆