返回类型与TypeScript中的输入类型相同

编程入门 行业动态 更新时间:2024-10-21 14:20:33
本文介绍了返回类型与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- blog.mariusschulz/2016/08/18/function-overloads-in-typescript#version-4-function-overloads

This has worked for me. All credit goes to Marius Schulz - blog.mariusschulz/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中的输入类型相同

本文发布于:2023-05-29 23:08:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/355071.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!