React Props Cheatsheet
Ignore Type Errors
Ignore TypeScript Errors on File
// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-nocheck
Ignore TypeScript Errors on Next Line
// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignore
Basic Props Types
type AppProps = {message: stringcount: numberdisabled: boolean}
Arrays And Object Props Tyes
Array
type AppProps = {names: string[]}
String Litteral Exact Values
type AppProps = {status: "loading" | "success" | "error"}
Objects
type AppProps = {/** interface with no required properties **/obj: {}/** useful placeholder **/obj2: object}
Single Object Multiple Types
type AppProps = {obj: {lkes: numberid: stringtitle: stringdescription: string}}
Array of Objects
type AppProps = {objArr: {id: stringtitle: stringdescription: string}[]}
Dictionaries
type AppProps = {dict: {[key: string]: TypeHere}}
or
type AppProps = {dict: Record<string, TypeHere>}
Function Types
type AppProps = {onClick: () => void}
type AppProps = {onClick: (id: number) => void}
Function Type with Event
type AppProps = {onChange: (event: React.ChangeEvent<HTMLInputElement>) => void/**alternative**/onClick: (event: React.MouseEvent<HTMLInputElement>) => void}
Other types
type AppProps = {optional?: OptionalType}
setState type
type AppProps = {setState: React.Dispatch<React.SetStateAction<number>>}
Typing React Component as Children
npm i @types/react
type FooProps = {children: React.ReactNode}export const Foo = ({ children }: FooProps) => {return <div>{children}</div>}
Examples
Simple Example of Baisc Prop Types
//....const App = () => {return (<div><Greet name="Ben"/><MessageCount count={5}><DarkToggle isDark={true}></div>)}
string
type
type GreetProps = {name: string}export const Greet = (props: GreetProps) => {return (<div><h3>Welcome to React TypeScript {props.name}</h3></div>)}
or
component/greet.tsx
type GreetProps = {name: string}export const Greet = ({name}: GreetProps) => {return (<div><h3>Welcome to React TypeScript {props.name}</div>)}
number
Type
component/message.tsx
type MessageProps = {count: number}export const Greet = ({ count }: MessageProps) => {return (<div><p>You have {count} messages</p></div>)}
boolean
Type
component/DarkToggle.tsx
type DarkToggleProps = {isDark: boolean}export const Greet = ({ isDark }: DarkToggleProps) => {return (<div><p>You are using dark mode {isDark ? "true" : "false"}</p></div>)}