我需要获取要与$ PropertyType实用程序一起使用的功能组件的类型。我该如何为我完成错误的工作?
// This code not work with component as function
function Button({loading, children}: {|
loading: boolean,
children: string,
|}) {
return (
<button>
{children}
{loading && <div className="loading"/>}
</button>
)
};
function SpecialButton({loading}: {|
loading: $PropertyType<$PropertyType<typeof Button, 'props'>, 'loading'>
|}) {
return (
<div>
<Button loading={loading}>
special text
</Button>
</div>
)
}
const specButton = <SpecialButton loading={10000}/> // <-- no error
// (its NOT OK for me)
答案 0 :(得分:0)
您可以声明类型ButtonProps
并在其上使用$PropertyType
吗?
import React from 'react';
type ButtonProps = {| loading: boolean, children: string |};
type SpecialButtonProps = {| loading: $PropertyType<ButtonProps, 'loading'> |};
function Button({ loading, children }: ButtonProps) {
return (
<button>
{children}
{loading && <div className="loading"/>}
</button>
)
};
function SpecialButton({ loading }: SpecialButtonProps) {
return (
<div>
<Button loading={loading}>
special text
</Button>
</div>
)
}
const specButton = <SpecialButton loading={10000} /> // Error!
另外,请查看How to validate optional fields with `$Diff`?,以获得有关如何键入React组件道具的更多提示。