Tom Le
Tom Le

Reputation: 127

How to return dynamic type depend on the parameter type in function

My code look like this

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

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

How can I define type of this function const withStyle = (customStyle)

Thanks for your help

Upvotes: 0

Views: 77

Answers (1)

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28757

You can use a type parameter in the type signature of the function, something like this:

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

This means that the function withStyle takes a single argument that is itself a function that takes something of type T, which is a subclass of TTheme and returns something else of type U.

It's not really clear from your question what the type signatures are, but the key is that you need to use generic type parameters.

Upvotes: 1

Related Questions