简体   繁体   English

获取<T>输入打字稿

[英]Get the <T> type in Typescript

For example in my case I need to reuse the type of a component in React ( React.FC ) but I want it with optionals props by using Partial<T> .例如,在我的情况下,我需要在 React ( React.FC ) 中重用组件的类型,但我希望通过使用Partial<T>将它与可选道具一起使用。

Is there a way to "get" the Generic <T> from that component type ( type TypeTargetComponent = React.FC<T> ) ?有没有办法从该组件类型( type TypeTargetComponent = React.FC<T> )“获取”通用<T> I would like to do something like : React.FC<Partial<XXXX<typeof TargetComponent>>> where XXXX is the "method" to get what I want.我想做类似的事情: React.FC<Partial<XXXX<typeof TargetComponent>>>其中XXXX是获得我想要的东西的“方法”。

type ExtractPropsType<T> = T extends React.FC<infer Type> ? Type : never; 

如果您键入typeof TargetComponent这应该有效

You can use the infer keyword.您可以使用 infer 关键字。

Something like this should work:像这样的东西应该工作:

Updated the answer to include example and fixed the type inferrence issue.更新了答案以包含示例并修复了类型推断问题。

type FC<T> = { data: T }

type InferredValueOf<Comp extends FC<any>> = Comp extends FC<infer T> ? T : never

type Derived<TargetComponent> = TargetComponent extends FC<any> ? FC<Partial<InferredValueOf<TargetComponent>>> : never

type TestType = Derived<FC<{ testValue: "value" }>>

const test: TestType = {
    data: {
        // testValue is optional now
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM