props-type
Utility type that defines the type of the React component props through propTypes
and defaultProps
in TypeScript
Table of contents
Installation
# with NPM $ npm install --save-dev props-type # with Yarn $ yarn add --dev props-type
Prerequisite
typescript
>= 2.8 (recommend 3.0+ because of support fordefaultProps
in JSX)@types/prop-types
>= 15.5.4
Usage
; // Without defaultProps; // With defaultProps;
Type Inference
isRequired
)
Optional (without defaultProps
without ;;
- Internal :
Props
type isdisabled: boolean | null | undefined
- External :
<Button disabled?: boolean | null | undefined />
defaultProps
with ;;;
- Internal :
Props
type isboolean
- External :
<Button disabled?: boolean | undefined />
isRequired
)
Required (with defaultProps
without ;;
- Internal :
Props
type isdisabled: boolean
- External :
<Button disabled: boolean />
defaultProps
with ;;;
- Internal :
Props
type isdisabled: boolean
- External :
<Button disabled?: boolean | undefined />
Example
defaultProps
without External
; ;
// Correct // Invalid // Property 'disabled' and 'onClick' is missing // Property 'onClick' is missing // Property 'disabled' is missing
- required :
disabled
,onClick
- optional :
className
,onDoubleClick
Internal
Button.propTypes = propTypes;
className
type :string | null | undefined
disabled
type :boolean
onClick
type :((...args: any[]) => any)
onDoubleClick
type :((...args: any[]) => any) | null | undefined
defaultProps
with External
; ; ;
// Correct // Invalid // Property 'disabled' and 'onClick' is missing // Property 'onClick' is missing // Property 'disabled' is missing // Type '(a: number) => void' is not assignable to type '(event: MouseEvent<HTMLButtonElement, MouseEvent>) => void'
- required :
disabled
,onClick
- optional :
className
,onDoubleClick
Internal
Button.propTypes = propTypes;Button.defaultProps = defaultProps;
className
type :string
disabled
type :boolean
onClick
type :((...args: any[]) => any)
onDoubleClick
type :(event: React.MouseEvent<HTMLButtonElement>) => void
null
or undefined
in defaultProps
External
; ; ;
// Correct // Incorrect
- required : N/A
- optional :
className
,testId
Internal
Button.propTypes = propTypes;Button.defaultProps = defaultProps;
className
type :string | null
testId
type :string | undefined
Limits
The prop type of oneOf
in prop-types
is not inferenced to union type.
; ; ; Button.propTypes = propTypes;Button.defaultProps = defaultProps;
type
prop is inferenced to string
(not a 'button' | 'submit' | 'reset'
union type) because prop-types
typescript type declaration currently have problems related to InferProps
type (in @types/prop-types
). If you want to inference oneOf
as union type, this workaround can help you.
;
Thanks
This package is inspired by Brie Bunge in Adopting TypeScript at Scale, JSConf Hawaii 2019
License
MIT © Taehwan Noh