我有两个函数可以做相同的事情,唯一的区别是输入类型和返回类型不同.我想知道如何将这些功能合并"为一个,其中一个想法是使用联合类型,但是我的约束是当输入是联合的一个成员时,返回值必须相同.
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中的输入类型相同
发布评论