如何获得函数的第一个参数的类型?



我想装饰功能并添加新的道具。我需要检测原来的道具类型和创建新的组合道具类型。如何检测OriginalProps类型从传递的功能没有泛型?

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"
})

你可以这样做:

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} />
}

打印稿操场

最新更新