I'm curious what the proper Flow annotation is for both render
methods in React classes, and simple return
s in stateless functions:
const UserProfilePage = () => {
return <div className="container page">
<UserProfileContainer />
</div>
};
By setting the return type intentionally incorrect (to a number), I got this error:
8: return <div className="container page">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ React element: `div`
8: return <div className="container page">
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ React$Element. This type is incompatible with the expected return type of
7: const UserProfilePage = (): number => {
^^^^^^ number
So, changing the code to this seems to satisfy Flow:
const UserProfilePage = (): React$Element => {
return <div className="container page">
<UserProfileContainer />
</div>
};
I'm wondering if this is correct, and if so, where is this documented?
Flow is a static type checker for your JavaScript code. It is developed at Facebook and is often used with React. It lets you annotate the variables, functions, and React components with a special type syntax, and catch mistakes early. You can read an introduction to Flow to learn its basics.
The Render Function The ReactDOM. render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.
Flow is a framework that, like TypeScript, promotes static typing in JavaScript. And like TypeScript it ships with React Native without any issues.
ReactElement is the type for elements in React, either created via JSX or React. createElement. ReactNode is wider, it can be text, number, boolean, null, undefined, a portal, a ReactElement, or an array of ReactNodes. It represents anything that React can render.
You don't need to annotate the render method, Flow should be able to infer the output type because it knows what JSX desugars to.
Flow has a built-in React interface, where all this stuff is defined:
declare class React$Element<Config> {
type: ReactClass<Config>;
props: $PropsOf<Config>;
key: ?string;
ref: any;
}
And then
render(): ?React$Element<any>;
So if you want to provide an explicit return type of a render method, you can use that signature. Well, maybe without a question mark if know you're not returning null. Not sure if there's any effect to omitting <any>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With