TypeScript条件类型:从react组件中提取组件props类型

Dyn*_*lon 6 types typescript reactjs conditional-types

使用打字稿2.8新的条件一般类型的特点,就是它可以提取TProps一个的React.ComponentType<TProps>组成部分?我想要一个类型,可无论是在工作ComponentType还是在TProps自身,这样你就可以-作为一名开发人员-通过这两个之一:

例如:

interface TestProps {
    foo: string;
}

const TestComponent extends React.Component<TestProps, {}> {
    render() { return null; }
}

// now I need to create a type using conditional types so that
// I can pass either the component or the props and always get the 
// TProps type back
type ExtractProps<TComponentOrTProps> = /* ?? how to do it? */

type a = ExtractProps<TestComponent> // type a should be TestProps
type b = ExtractProps<TestProps>     // type b should also be TestProps
Run Code Online (Sandbox Code Playgroud)

这可能吗,有人可以提供解决方案吗?

Seb*_*ber 7

有一个内置的助手

type ViewProps = React.ComponentProps<typeof View>

/sf/answers/3850413171/


Tit*_*mir 5

这是条件类型及其推理行为的非常直接的应用(使用infer关键字)

interface TestProps {
    foo: string;
}

class TestComponent extends React.Component<TestProps, {}> {
    render() { return null; }
}

type ExtractProps<TComponentOrTProps> = TComponentOrTProps extends React.Component<infer TProps, any> ? TProps : TComponentOrTProps;

type a = ExtractProps<TestComponent> // type a is TestProps
type b = ExtractProps<TestProps>     // type b is TestProps
Run Code Online (Sandbox Code Playgroud)


Sle*_*ker 5

我建议使用React.ComponentType,因为它还将包括功能组件:

type ExtractProps<TComponentOrTProps> =
  TComponentOrTProps extends React.ComponentType<infer TProps>
    ? TProps
    : TComponentOrTProps;
Run Code Online (Sandbox Code Playgroud)