首页 > 解决方案 > 如何返回动态类型取决于函数中的参数类型

问题描述

我的代码看起来像这样

const styles = ({palette, appStyle}: TTheme) => ({
  component: { backgroundColor: palette.primary},
  text: appStyle.text,

const withStyle = (customStyle) => 
  customStyle({
    palette: { primary: 'red'},
    appStyle: {text: {color: 'red'}},
  })

如何定义此函数的类型const withStyle = (customStyle)

谢谢你的帮助

标签: reactjsfunctiontypescript

解决方案


您可以在函数的类型签名中使用类型参数,如下所示:

function withStyle<T extends TTheme, U>(styles: (T) => U) {
  ...
}

这意味着该函数withStyle接受一个参数,该参数本身就是一个接受某种类型的函数,该类型T是 的子类TTheme并返回其他类型的东西U

从您的问题中并不清楚类型签名是什么,但关键是您需要使用泛型类型参数


推荐阅读