Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional react useState types with jsdoc, typescript checkjs (javascript)

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

like image 234
schpet Avatar asked Oct 09 '19 21:10

schpet


People also ask

Can you use JSDoc with TypeScript?

You can use most JSDoc type syntax and any TypeScript syntax, from the most basic like string to the most advanced, like conditional types.

What is TypeScript type for React component?

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.

What is IntrinsicAttributes?

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.

How do you add type to useState?

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!


1 Answers

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)
like image 157
yongming zhuang Avatar answered Oct 04 '22 02:10

yongming zhuang