1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.