简体   繁体   中英

How to type state in React Hooks without adding typescript (like prop-type - in a simple way)

Just wonder.

If I don't want to add TS to my React project, but I need sometimes some types checking.

While for props I have a simple solution of prop-types, for state I can't do nothing.

So is there is some solution for that?

import PropTypes from 'prop-types';
//https://reactjs.org/docs/typechecking-with-proptypes.html - prop-types

    
export  function GreetingHook (props) {
    
    const [name2, setName2] = useState(10);//won't generate a warning.

    {
        return (
            <h1>Hello, {props.name}</h1>
        );
    }
}

GreetingHook.propTypes = {
    name: PropTypes.string,
    name2: PropTypes.string
};

//Some parent...
//Will generate a warning
<GreetingHook name = {5}/>

NB - The same question should be asked about class component too.

You can use flow instead of typescript, and for typechecking you can do it in this way:

const [name2, setName2] = useState(10);
(name2: number);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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