aryzing
aryzing

Reputation: 5877

How to get type of component props, when component defined with type parameters

Although React.ComponentProps<MyComponent> is quite handy, I'm unable to figure out how to use it to construct a type of MyComponent's props, when MyComponent contains type parameters, eg (shortened type taken from a module)

declare type TMyComponent = <T = unknown>(props: {foo: string, bar: T}) => ReactElement

Somehow, using TMyComponent, I'd like to construct the type, eg, {foo: string, bar: number}

Although the following doesn't accomplish what I'm trying to do, I hope it demonstrates what I'm trying to do,

type MyDesiredType = React.ComponentProps<TMyComponent<number>>

How can I construct a type from a component's props that accepts type parameters?

Upvotes: 1

Views: 615

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53964

The generic syntax should be near the type, same goes for default type, in your case the "unknown" is a default variable in JS syntax.

type TMyComponent<T = unknown> =(props: {foo: string, bar: T}) => React.ReactElement

type MyDesiredType = React.ComponentProps<TMyComponent<number>>
// Resolves to
type MyDesiredType = {
    foo: string;
    bar: number;
}

type MyDesiredTypeUnknown = React.ComponentProps<TMyComponent>
// Resolves to
type MyDesiredTypeUnknown = {
    foo: string;
    bar: unknown;
}

TS Playground

Upvotes: 1

Related Questions