here is my code:
// impl GetProps<"html-element"> like GetProps<"div">
export type GetProps<T extends ElementType> = ComponentPropsWithoutRef<T>
// impl GetProps<Component>
export type GetProps2<T extends Component> = ComponentPropsWithoutRef<new () => T>
I expect merge GetProps and GetProps2 into one GetProps, and make support syntax GetProps<Component>
and GetProps<"div">
, how to do?
CodePudding user response:
In order to do that, you just need to create conditional type:
import { Component, ComponentPropsWithoutRef, ElementType } from 'react'
// impl GetProps<"html-element"> like GetProps<"div">
export type GetProps<T extends ElementType> = ComponentPropsWithoutRef<T>
// impl GetProps<Component>
export type GetProps2<T extends Component> = ComponentPropsWithoutRef<new () => T>
type Result<T extends ElementType | Component> =
(T extends ElementType
? ComponentPropsWithoutRef<T>
: (T extends Component
? ComponentPropsWithoutRef<new () => T>
: never)
)
type Test = Result<'div'>
CodePudding user response:
I find simple solution, use ts conditional type ?type:type2
, see following code
// @ts-ignore ComponentPropsWithoutRef<new () => T> in webstorm is raised syntax err but in typescript compile and runtime it work
export type GetProps<T extends ElementType | Component> = T extends ElementType ? ComponentPropsWithoutRef<T> : ComponentPropsWithoutRef<new () => T> // `new () => T` means `typeof T`