[英]Use the generic of a const as an interface
I'm using react-intl and they have a TypeScript definition for a FormattedNumber component:我正在使用 react-intl 并且他们有一个 FormattedNumber 组件的 TypeScript 定义:
export declare const FormattedNumber: React.FC<UnifiedNumberFormatOptions & CustomFormatConfig & {
value: number;
}>;
I'm using this in my React component that takes a prop usdProps
allows you to override the props of a FormattedNumber component:我在我的 React 组件中使用它,它接受一个道具
usdProps
允许您覆盖 FormattedNumber 组件的道具:
<FormattedNumber
value={numAmount}
style="currency"
currency={unit}
minimumFractionDigits={2}
maximumFractionDigits={2}
{...usdProps}
/>
How can I set the props of my component to be generic of FormattedNumber without copying that exact generic?如何将我的组件的 props 设置为 FormattedNumber 的泛型而不复制那个精确的泛型?
Right now I can do this:现在我可以这样做:
interface Props {
usdProps?: UnifiedNumberFormatOptions &
CustomFormatConfig & {
value: number;
};
}
But I'd prefer it to be directly coupled to FormattedNumbers (fake example):但我更喜欢它直接耦合到 FormattedNumbers(假示例):
interface Props {
usdProps?: genericsOf FormattedNumbers;
}
Assuming that the type React.FC<T>
depends structurally on its generic type parameter T
(ie, it actually uses T
as opposed to ignoring it ), then you should be able to use conditional type inference to extract T
from React.FC<T>
, like this:假设类型
React.FC<T>
结构上依赖于它的泛型类型参数T
(即,它实际上使用T
而不是忽略它),那么您应该能够使用条件类型推断从React.FC<T>
提取T
React.FC<T>
,像这样:
interface Props {
usdProps?: typeof FormattedNumber extends React.FC<infer T> ? T : never
}
You can verify that this type is the same as your manual version.您可以验证此类型是否与您的手动版本相同。
Okay, hope that helps;好的,希望有帮助; good luck!
祝你好运!
You want to extract the props of a component to use it in your own component.您想提取组件的 props 以在您自己的组件中使用它。 But there is no way to do that.
但是没有办法做到这一点。
Since the props where declared using the generic type <UnifiedNumberFormatOptions & CustomFormatConfig & { value: number; }>
由于使用泛型类型声明的道具
<UnifiedNumberFormatOptions & CustomFormatConfig & { value: number; }>
<UnifiedNumberFormatOptions & CustomFormatConfig & { value: number; }>
if you want to use it you need to declare it the same way. <UnifiedNumberFormatOptions & CustomFormatConfig & { value: number; }>
如果你想使用它,你需要以同样的方式声明它。
What you can do to achieve the same result is declare it as a type:您可以做些什么来实现相同的结果是将其声明为类型:
type FormattedNumberProps = UnifiedNumberFormatOptions & CustomFormatConfig & { value: number; };
and use it on your interface:并在您的界面上使用它:
interface Props {
usdProps?: FormattedNumberProps;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.