[英]Can't get babel to compile string literal type with interpolation on typescript
[英]Get the <T> type in Typescript
例如,在我的情况下,我需要在 React ( React.FC
) 中重用组件的类型,但我希望通过使用Partial<T>
将它与可选道具一起使用。
有没有办法从该组件类型( type TypeTargetComponent = React.FC<T>
)“获取”通用<T>
? 我想做类似的事情: React.FC<Partial<XXXX<typeof TargetComponent>>>
其中XXXX
是获得我想要的东西的“方法”。
type ExtractPropsType<T> = T extends React.FC<infer Type> ? Type : never;
如果您键入typeof TargetComponent
这应该有效
您可以使用 infer 关键字。
像这样的东西应该工作:
更新了答案以包含示例并修复了类型推断问题。
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.