Home > OS >  How to get type of first argument of function?
How to get type of first argument of function?

Time:09-27

I want decorate function and add new prop. I need detect original props type and create new combined prop type. How to detect OriginalProps type from passed function without generic?

const addAgeProp = (Component)=> {

  type OriginalProps = ???  //typeof Component first arg, how to?
  type CombinedProps = OriginalProps & {age: number}

  return (props: CombinedProps)=> {
    return <Component {...props}/>
  }
}


interface Props {
  name: string
}

addAgeProp((props:Props)=> {
  props.name // type "string"
  props.age // type "number"
})

CodePudding user response:

You can do this:

import React from 'react';

function addAgeProp<P>(Component: React.ComponentType<P>) {

  type OriginalProps = React.ComponentProps<typeof Component>;
  type CombinedProps = OriginalProps & { age: number }
  
  // Or, more simple
  // type CombinedProps = P & { age: number }

  return (props: CombinedProps) => {
    return <Component {...props} />
  }
}

interface TestComponentProps {
  title: string;
}
function TestComponent({ title }: TestComponentProps) {
  return <div>{title}</div>
}


const TestComponentWithAge = addAgeProp(TestComponent)

function App() {
  return <TestComponentWithAge title='test' age={12} />
}

TypeScript Playground

  • Related