using typescript's jsdoc support to type the following javascript code:
const [optionalNumber, setOptionalNumber] = useState(null)
const handleClick = () => {
setOptionalNumber(42)
// ^-- Argument of type '42' is not assignable to parameter of type 'SetStateAction<null>'
}
the way i currently get around this works but is a bit ugly:
const [optional, setOptional] = useState(
/** @type {number|null} */ (null)
)
how can i accomplish this without using casting? i want optional
to have a type of null | number
, and setOptional
to only accept null | number
as an argument.
codesandbox demonstrating this:
https://codesandbox.io/s/optimistic-villani-kbudi?fontsize=14
You can use most JSDoc type syntax and any TypeScript syntax, from the most basic like string to the most advanced, like conditional types.
Within TypeScript, React.Component is a generic type (aka React.Component<PropType, StateType> ), so you want to provide it with (optional) prop and state type parameters: type MyProps = { // using `interface` is also ok message: string; }; type MyState = { count: number; // like this }; class App extends React.
IntrinsicAttributes interface can be used to specify extra properties used by the JSX framework which are not generally used by the components' props or arguments - for instance key in React.
To type the useState hook as an object in React, use the hook's generic, e.g. const [employee, setEmployee] = useState<{name: string; salary: number}>({name: '',salary: 0}) . The state variable will only accept key-value pairs of the specified type. Copied!
I think you can define an initial value with the correct union type and pass it to useState
.
It would be something like this:
/**
* @type {number | null}
*/
const initValue = 42;
const [optionalNumber, setOptionalNumber] = useState(initValue)
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