I have a simple React component that adds two numbers together. It’s written in TypeScript and using @types/prop-types.
import React from 'react'; import PropTypes from 'prop-types'; const AddPropsTypes = { first: PropTypes.number, second: PropTypes.number }; type Props = PropTypes.InferProps<typeof AddPropsTypes>; const Add: React.FC<Props> = ({ first = 1, second = 2 }) => { return <div>{first + second}</div>; }; Add.propTypes = AddPropsTypes; export default Add;
Typescript complains that first
and second
could possibly be ‘null’ ts(2531), but they have default parameter values.
Making these PropTypes.number.isRequired
will obviously make the warning go away, but I don’t want them required.
I know I can make this warning go away with <div>{(first || 1) + (second || 2)}</div>
within the jsx, but I shouldn’t have to define the default values twice. Currently, I’m ignoring the warning with the following above the line:
{/* lol https://github.com/Microsoft/TypeScript/issues/27552 // @ts-ignore */}
Is there any way to define the PropTypes
or InferProps
so it knows about the default parameter values?
Advertisement
Answer
Use non null assertion operator !
first! +second!