0% found this document useful (0 votes)
27 views35 pages

Typescript Cheatsheets

The document provides a comprehensive cheatsheet for experienced React developers transitioning to TypeScript, covering basic and advanced usage, setup, and troubleshooting techniques. It includes sections on function components, hooks, and migrating from JavaScript, along with practical examples and best practices. The goal is to facilitate effective use of TypeScript in React applications without overwhelming users with complex type logic.

Uploaded by

Manasses
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
27 views35 pages

Typescript Cheatsheets

The document provides a comprehensive cheatsheet for experienced React developers transitioning to TypeScript, covering basic and advanced usage, setup, and troubleshooting techniques. It includes sections on function components, hooks, and migrating from JavaScript, along with practical examples and best practices. The goal is to facilitate effective use of TypeScript in React applications without overwhelming users with complex type logic.

Uploaded by

Manasses
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
26106725, 00:37 GitHub -ypess 1 typescript-cheatsheets /react Pi crptcheatsheotsireact:Cheatsheets for experienced React developers geting started with TypeSeript cheatsheets for experienced React developers geting started with Typescript @ reacerypescptcheatsheetnetliyapp 8 MAT conse fr Msakstrs Y A2k tors BF Branches su © Code Q issues 112 Pullraquest © ngs Acivty 2h Netteatons ts GD Dicusions © Acions © Security Le tights P min > | PB tBranch Oona FO Q Getafe Goto te & heyahdveduy Ipcttvent in forme-andeovntss (781) Miata: tetmenh © Be situ chor: Update actions/setperade tov (748) 8 month 90 Be husly upgrade musty (#528) 3 yeas 290 Be docs outtvent in forms-and-events md (4781) bostmonth Be website fie sled ising at tio (745) ‘8 months ago D aticontibstorre doce a sasus 36 contributor for doe (8708) bast yar DD docterignore ‘Wi plement Docenurs (e214) S years 390 B sitgnore Move comvbuting pages rm docs to pages yeas 290 DD mre chore: Update ations setparose tov (768) ‘8 months ago D contasutneme ‘updated CONTRIBUTING mode it beter pr 2 years 390 1 conraisuT0RS ms doce acl sass 363 contributor for doc (#704) bt year DB ucense nti commit 7 yeas ag0 D reaomeme ‘oattvent in forms-and-events nd (#78) bostmonth D code-otcondctmd Code of Cond to repository (0554) Byars a9 D coyiejs Move convibuting pages rm docs to pages ( years 390 D genteasmajs removed unused excess code (4547) 2 yeas 200 DB metitysomt tty tond yeas ag0 B packagejson upgrade mek (85251 3 year 990 D yamtoee parade hot (0528) 3yearsa90 React TypeScript Cheatsheet Cheatsheet for using React with TypeScript. Web docs | Contribute! | Ask! This repo is maintained by @epstlon and efliptarnnes Lard, We'e so happy you want to try out React with TypeScript If {you see anything wrong or missing, please file an ieeue! -npsufgthub.comtypescrgt-cheatsheotsreact7tabsreadme-ov-fleoption-1-dom-olomentref 1195 26106725, 00:37 GitHub - typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript ‘The Basic Cheatsheet is focused on helping React devs just start using TS in React apps '© Focus on opinionated best practices, copy pastabe examples, ‘© Explains some basic TS types usage and setup along the way. (© Answers the most Frequently Asked Questions © Does not caver generic type logic in detail Instead we prefer to teach simple troubleshooting techniques for newbies. ©The goal i to get effective with TS without leaning too much TS. + The Advanced Chestshest helps show and explain advanced usage of generic types for people writing reusable type sitiestunctons/render rop/higher order components and T+ React libraries. © Iealso has miscellaneous tips and tricks for pro uses. © Advice for contributing to DefiitelyTypes. © The goal is o take fll advantage of TypeScript ‘The Migrating Cheatsheet helps collate advice for incrementally migrating large codebases from JS or Flow, from people who have done x 1© We do nat try to convince people to switch, only to help people who have already decided, © A, This is anew cheatsheet all assistance is welcome. + The HOC Cheatsheet specifically teaches people to write HOCS with examples, ‘© Familiarity with Generics is necessary © A, This isthe newest cheatsheet, all assistance is welcome. Basic Cheatsheet Basic Cheatsheet Table of Contents ‘¥ Expand Table of Contents React TypeScrpt Cheatsheet © Basic Cheatsheet = Basic Cheatsheet Table of Contents * Section 1:Setup 1 Prerequisites React and TypeSeript starter kits + Try React and TypeSeript online * Section2: Getting Stated ' Function Components wsestate useCallback + useReducer = Option 1: 00M element raf = Option 2: Mutable value raf = See so + uselmperatveHandle + More Hooks + TypeScrpt reading + ample React Hooks + TypeScript bates: + Class Components + Typing getDerivedstatetromProps + You May Not Need defauteProns + Tying setautemops + Consuming Props af a Component with defaulPrope * Problem Statement = Solution 1 Mise Discussions and Knowledge, + Tying Component Props ' Basic Prop Types Bamoles -nps:fgthub.comtypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentref 26106725, 00:37 GitHub typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript 1 bject_a5 the non-primitive type = Empty interface, (and object Useful React Pr Type xamples or interfaces? = Toe = More Advice = Useful table for Types vs Interfaces © getDerivedstatefrom?rop rms and Events Uist of event types = Context 1 Basic example Without default contort value 1 Tyge assertion as an alternative = forwardRet/createRet Generic forwardRets * Option 1 = Wrapper component + Option 2 Redeclare forardRef + Option 3 = Call sionature 1 More nfo 1 Portals Error Boundaries * Option 1: Using react-eror-boundary * Option 2: Writing your custom efror boundary component 1 Concurrent React/React Suspense 1» Troubleshooting Handbook: Types + Union Types and Type Guarding + Optional Types, + Enum Types + Tune Assertion * Simulating Nominal Tynes © Intersection Types * Union Types, * Overloading Function Types, 1 Using inferred Types| Using Partial Types, 1 The Types need werent exported! 1 The Types need dont exist! "Slapping, any on everthing 1 Autopenerate types 1 Typing Exported Hooks 1 Typing Exported Components Frequent Known Problems with TypeSerpt 1 Troubleshooting Handbook: erators ' Troubleshooting Handbook: Utilities 1» Troubleshooting Handbook: tsconfigjson 1» Troubleshooting Handbook: Fixing bugs in offical ypings 1» Troubleshooting Handbook: Global, Images and ather nan-TS fles = Editor Tooling and integration = Gnting 1 Other React + TypeScrint resources 1 Recommended React + TypeScr = Time to Really Leatn TypeSeript talks © My question isn't answered here! -nps:fgthub.comtypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentref 26108125, 00:37 GitHub typescipt-cheatsheetsteact: Cheatsheet fr experienced React developers getting stated wth TypeScript © Contributors Section 1: Setup Prerequisites You can use this cheatsheet for reference at any sil lvel, but basic understanding of React and TypeScriptis assumed, Here is list of prerequisites + asic understanding of React ‘+ Familiarity with Typescript Basis and Everyday Types. In the cheatsheet we assume you are using the latest versions of React and TypeScript. React and TypeScript starter kits React has documentation for how to start a new React project wth some of the most popular frameworks. Here's how to star them with Typescript + Nextt mph ereste-next-appelatest --ts Romie npe create-remtapiatest Gatsby: apm inst gatsty ts + Sapo! mpx crestecexpo-app -t with-typesertpt ‘Try React and TypeSerpt online There are some tools that let you run React and TypeScrpt online, which can be helpful for debugging or making sharable reproductions. + TypeSerint playground + sackit + CodeSandooe Section 2: Getting Started Function Components ‘These can be written as normal functions that take a. preps. argument and return a JSX element 11 beclaring type of props - see “Typing Conponent Props” for nore exenples e *yp0 Aopieops = { nessage: strings Bs [7 ase “interface” <6 exporting £0 that consuens can extend */ const dep = ({ nessage }: AppProps) =>
{nessage)
; const nop = ({ message }! Appbrops): React. ISK. Clenent =>
{nessage)
; const nop = ({ message }: { nessage: string }) => célvo(nessage) 11 aasernatively, you can use “React FunctionCanpanent™ (or “React.FC'), if you prefer 71 wath latest React types and TypeScrigt 5.4. st's aostly a stylistic choice, otherstse discouraged const Aap! React FurctionConponenteg message: string }> = (( message )) => ( “avo message} /aiv> % Wh or const Aap: React FCetgpProps> = ({ message }) => cdivo{nessage}s Tip: You might use Paul Shen's VS Code Extension to automate the type destructure declaration fine! a keyboard shart) > Why is nesct.fe not needed? What about React.FunctSonConponent / Resct.VotdFunctienConponsnt ? Hooks Hooks ae supported in gtyoes/react from v168 up. useState ‘Type inference works very wel for simple values: -nps:fgthub.comtypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentref 26106725, 00:37 GitHub typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript const (state, setstate] = usestate(false); CJ Wes only takes booleans See also the Using nfered Types section if you need to use a complex type that you've relied on inference for However, many hooks ae initialized with null-ish default values, and you may wander how to provide types. Explicitly declare the type, and use 3 union ype: const (user, setuser] = usestatecuser | null>(oull)s cy U1 aster sotueer(neser)s ‘You can also use type assertions ita states intialized soon after setup and always has a value after const (user, setuser] = usestatecisero({) a5 User); e setuser(nser)s ‘This temporarly‘lies"to the TypeScript compiler that {) is of type User. You should fallow up by setting the user state —ifyou dom’, the rest of your code may rely on the fact that user is of type User and that may lead to runtime errs useallback You can type the usecatiback just lke any other function, const menotzeecalTbace = ysecal back e (arama: string, param: runter) => ( console. log(oarant, paran2) Fetern {/ott true} » recy > fo + (param string, paran2: nunber) => ( okt Note that for React < 18, the function signature of usecsltbace typed arguments as ary{1 by default: ‘function useCallbackeT extends (...argst any(]) => anye( e callback: Ts eps: opendencytist “Tt In React > 18, the function signature of usecatiback. changed to the following function usecal1backeT extenés Function>(callback: Ts deps! DependencyList): Ts e@ ‘Therefore, the following code will yield” Paraeeter “e' Snplicitly has an ‘any” type." ervor in React >= 18, but not <17 11 @ts-expect-error Paraneter ‘e* inplicitly has ‘any" type. e secaldoack((e) => Os (Ds 1) expliest “any” type secal back (et any) => Qe (D5 useReducer ‘Yu can use Disriminated Unions for reducer actions. Don forget to define the return type of reducer, otherwise TypeScrpt wil infer it ngort { useRecucer } from “reacts e const Anstlalstate = { counts @ ): -npsfgthub.comtypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentef 5195 26106725, 00:37 GitHub typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript 1 Cpe: | Crype: revere ‘function reducer(state: typeof Initiaistate, action: ACTIONIPE) ( suiten (action.type) ¢ return { count: state.count + action-payload 3s return ( count: state.count ~ Nunber(action.payload) eotauie ‘rot pew Eever Os ) ? function counter() { Const (state, dispatch] = usetedicer(reducer, initcalstate); return ( ‘cour: (state-court} button onclicke(() => éispetcn({ type: “eecrenent”, payload: "5" > youston> button onclicke{() => dispatcn({ type: Tinerenent”, payloae: 5 ))> croutton> a ‘View in the TypeSeript Playground Usage with Reducer from redux usebffect / useLayoutEffect Both of useeffect and usetayoutttfect_are used for performing side effects and return an optional cleanup function which means if they don't deal with returning values, no types are necessary. When using usectfect, take cae not to retuin anything other than function oF undefined , otherwise both TypeScript and React wil yell at you. This can be subtle when using arrow functions: Tunction DelayedEfrect(props: { timers: number }) { e const { timers } = proas: sseesece¢ o> settineoit(Q) > ( 2 tines), [inert] % 7 bad example! see Timeout Seplicitiy returns a nurter ? > Solution tothe above example useRef In Typescript. usenet retusa reference thats ether read-only or mutable, depends on whether your type argument flly covers the intial value or not. Choose one that suits your usecase Option DOM element af ‘To1access a DOM element: provide only the element type a5 argument, and use suil_ as intial value. In this case, the returned reference will have 8 read-only current. thats managed by React. TypeScript expects you to give this ref to an element's ref prop: function Foot) { e 11 = Xf possible, prefer as specific 2s possible, F {i = Technical-wise, this returns RefOoject HTML const aivRef ~ vseher(M411)5 seefect(() => -nps:fgthub.comtypescrgt-cheatsheotsreact7tabsreadme-ov-fleoption-1-dom-olomentsef 6135 26106725, 00:37 GitHub - typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript Sf (lobviet.cunrent) throw Errar("aivRef Ss rot assigned”); 11 Now divkes current 4 sure to be WIALDivElenent esonethingath(divfet. current); » 1 Give the ref to an element so React can manage St for you return caty nef-(oivRer}>ete3, > It you are sure that aivier.current ll ever be null itis also possible to use the non-null assertion operator const diet = veeteF Tip: Choosing which HTALElenent to use ‘Option 2: Mutable value ref “To have a mutable value: provide the type you want, and make sure the iil value fully belongs to that type: function Foot) { e 11 Teehrical-wise, this returns hutablenefObjecterumber | null> const intervaltef = useRefémunber | mil1s{oul2); 11 You nanage the ref yourselt (shat's why St°5 called MutableRefO2jee!1) secerect(() => ¢ ‘sntervalRef current = settnterval(...34 return () = clesrircervol(ntevalief current); » 0% return ebutton onclicke(/* clearinterval she ref */]>Cancel tiner((orops, ref) => { retnporativerancleteet, () => (C 11 stareQ) has type faerence here start) ¢ sere ("start=)3 » DH return ealvscountdowne/iy>i Mm 11 The conpanent uses the Countdown component e Snoort Countdown, { CountdenotindLe } fron *. Countdown. tex" -npsufgthub.comitypescrgt-cheatsheotsreact7tabsreadme-ov-fleoption-1-dom-olomentsef 7135 26106725, 00:37 GitHub typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript function apa) { fonst countdomh = ysoie“(0ull)3 seerect(() => ¢ AF (countdomel current) { 1] Start() has type inference here 2s well courtdownelcurrent-stortQ)s > » On ? {countdown /95 See alo + Using ForardRefRenderFunction ‘Custom Hooks I you are returning an array in your Custom Hook, you will want to avoid type inference as TypeScrpt will infer a union type (when you actually want differen types in each positon ofthe array). Instead, use TS 3.4 const assertions noone { usestate } (ron "reace" @ xgort function vsstoasinat) ( ones [Ssloading, ret State] = usestate(*als9); const load = (3Prorise: Pronisecany>) => { setstate(tra)s return aProntse.FinalIy(() % Feturn [Isloading, load) as const; // infers (Boolean, typeof Joad) instead of (Boolean | typeof Load) > setstate(false)): ‘View in the TyoeScrpt Playground ‘This way, winen you destructure you actually get the right types based on destructure position > Alternative: Asserting a tuple return type Note that the React team recommends that custom hooks that return more than two values should use proper objects instead of tuples, however More Hooks + TypeScript reading: «+ ntps//medium com/@jnwebdeu/react-naoks-n-typescrpt-BBfce7001d0d « htps /ettbog cu/typescriptreact/nooks/#useret you are writing a React Hooks library, don't forget that you should also expose your types for users to use Example React Hooks + TypeScript Libraries: + htps/olthub com/mueststrate/use-st8 + htps/oithub.com/palmeshay/tne-platform * ntps/ithub comysw-yadhooks Something to add? Fle an issue. ‘class Components Within TypeScrint,Resct.Conponent isa genetic type (aka React.Conponsnt ), so you want to provide i with optional) prop and state type parameters ‘type myrrops = « eo 77 using “interface” 4s also ok ressage: string: B type mystate = { court: munaers // Tike *his lass nop extends React. Canponentayprops, Mystate> state! wystate = { 11 optional second ara n for better type inference -npsufgthub.comitypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentef 8195 26106725, 00:37 GitHub - typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript % reneert) ( retura “this. props. message) (Unis. state.count) » ) > ‘View in the TypeScrpt Playground Don’ forget that you can export/import/extend these types/interfaces for reuse > Why annotate state twice? > Noneed for resdoniy ‘Class Methods: Do it ke normal, but just remember any arguments for your functions also need to be typed lass Pop extends Ranct.Conponentet sage: string J» { counts number }> ( e state < {cot ©}; rengert) return (
this-inerenent(2)}> (this.props.nessage) {this. state. court) aw » > fncrenert = ant: number) => ( 11 ike ee thls. serstate((statey > (( README @ Code ofconduct HB MIT Ieense ? ‘View in the TypeSerpt Playground ‘lass Properties: ityou need to declare clas properties for later use, just declare it ike state , but without assignment class nop extends React, Conporente, e@ pe pointer: numbers // Jske this fenponertBieieunt() { ‘this. pointer = 3; > Fengert) { return ( ‘ths. props.nessage) and (ehis. pointer) ros0> % ‘View in the TypeSerpt Playground Something to add? File an issu, ‘Typing getDerivedstateFromProps Before you start using getberivedstateFronProps, please go though the dacumensation and You Probably Don't Need Derived State, Derived Sate can be implemented using hooks which can also help set up memoization. Here are afew ways in which you can annotate getderivedstateFranProps 1. fyou have explicily typed your derived state and want to make sure that the return value from gatoarivedstateFrenProps conforms toi ‘lass comp extends React.Conponent { e statle geiberivedstateFronPreps( -nps:fgthub.comitypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentsef 9195 26106725, 00:37 GitHub - typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript ): Partiahestates | null ¢ > 2, When you want the function’ return value to determine your state. class Conp extends React. Componente euratypectypeot Campi "getberSvedstaterronProps"]> statle geaberivedstateFronProps(props: Props) 3. When you want derived state with other state fields and memoization| type Custowvalue = anys interface Props { propht Custonvatue; > “Sntortace befnedseate ( otherstaterield: strings ? Function transfornPropstostate(props: Props) ( retara SsavedProat: props.proah, // save for nenotzation eriveestate: props.propt, » > ‘lass conp extends React. PuneComponentcProps, State> ( constructor(Props: Props) super(orops)s this.state = ( ‘therseateriels: “123°, rans(ornPropeTostate(erops), » > Statle geaberivedseateFrenProps(props: Props, state: state) { Af (UsEqal(props.proph, state. saved?roph)} return null: return transforsPropetostate prope): > ? View in the TypeScrpt Playground You May Not Need defaultProps [As per this weet, defaultProps will eventually be deprecated. You can check the discussions here: + Original west ‘© More info ean also be found in this article The consensus is to use object default values. Function Components: ype GreetProps = ( 296?! nunber ): const Greet = ({ age = 2 J GreetProps) => // Class Components ype GreetProps = ( age?! numens # clase Gre encert) ( const (age = 22.) = thie.aropss Pot ? -nps:fgthub.com/typescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentef cxtonds React Component GreetProps> { e e 10135 26106725, 00:37 GitHub typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript ? ot ol = coreet a86=(3) 3 ‘Typing defaultProps Type inference improved greatly for defaultProps in TypeScript 204, although some edge cases are sill problematic, Funetion Components 11 using typeof as 2 shortcut; note that st moist 11 you can also declare the type of DefaultProps if you choose 11 ove. wisps /esthid.con/typescript-chestaneets/nenct/sssues/415ALssbecomnent-881223219 ‘ype Grestrrops = ( age: number ) 8 typeot geraultPropss const Greet = (prope: GreetProps) => ( ie » ‘reat.defaultProps = defoultPropss See this in TS Playground For Class components there are 3 couple ways to doit neluding using the Pick tity ‘ype) but the recommendation isto "reverse" the props definition: type GreetProps = typeor Greet defaultProps & get munbers % clase Greet oxtends foact.ConpanenscGreetProps> 11 Type-checes! no type assertions necced et el = coreet ag6-(3) (23 > noact. 254. Librarytanagedatensbutes nuance fr library authors Consuming Props of a Component with defaultProps ‘Acomponent with defauiterops. may seem to have some reauied props tha actualy aren't Problem Statement Here's what you want to do: interface 1Props ¢ ame! strings const defoultProps age! 25, Const Greetconponent = ({ nan, age ): TProps & typeof defaultProps) => ¢ »% ‘Sreatconponent.defauitorons = deraultPronsi const Testconponent « (props: React ConpanentPropsctypeof GreetConponents) => ¢ return 11 Property “age” $5 missing Ln type “{ mane: string: )° but required £9 type “(ages nunbe const el = cTestConponentnane="fe0" />; -nps:fgthub.comtypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentref e e 11135 26106725, 00:37 GitHub - typescript choatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript Define autlty that applies neact.254.Librarymanagesnttributes| type ConponentPropset> = T extends e | ReactconporentIyzeciater ?> | React conporentclnter 2 React 35%. LibrarymanagedattrsbutescT, P> const Test onponent = (props: ConponentPropsctypeof GreetConporent>) return 5 See this in TS Playground Discussions and Knowledge > Why does neact.Fe break defauitprone ? > TypeScript 2.9 and ea Something to add? Fle an issue ‘Typing Component Props ‘hiss intended as» basic orientation and reference fr React developers fanilarzing with TypeSeript Basic Prop Types Examples Allis of TypeScrot types you wil ikely use in a React+TypeScrip app ype AapPrens = ¢ @ essage: strings ‘saablee: sooleans array of 2 type! */ stringt ls status: “waiting” | "success" - . 07 an object with krow properties (but could have nore at runtine) */ ob: { tutte: strings » cbjare: { 4: strings 20 [5 any ron-printtive value ~ can't access any properties (NOT COMMON but useful ab placeholder) +7 onjas object: (ran interface with no required properties - (WOT COMIN, except for things Like “React.Conponentc(), state>”) */ ey OF + a dict object with any runber of properties of the sane type */ dieu: ( ring): MyTypehere; ‘lee2: Recordestring, Mylypaeres; // equlvatent to dsett fanetion that doesn't take or return anything (VERY COWEA) */ fnctice: () => wold; on with tare arop (VERY COMON) */ onchange: (46: number) => vod; (7 function type syntax that takes an event (VERY COMER) */ foncnange: (event: React. ChangeEventMiInputtlenent>) => voids (r= aiternative function type syntax shat takes an evert (VERY COMON) lonclicc(event: React.WousetventmTMLButtontlenent>): voids (r= any fonction as long a5 yOu don't snvoke 42 (not reconmended) */ fonsonething: Function; jr an optional prop (VEN Cl cptionsl?: optional ype; sox!) #7 -nps:fgthub.comitypescrgt-cheatsheotsreact7tab=readme-ov-fle¥option-1-dom-olomentef 12195 26106725, 00:37 GitHub typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript sotStater React DtspatendRoact.SetStatekctioncnunbers> B ject a the non-primtive type object Is 8 common source of misunderstanding in TypeScrpt. It does not mean ‘ary object” but rather “any non-primitve type", which means it represents anything that isnot navber, bigint, string, boolean, synbol , null or undefines “Typing “any non-primitive vale” is most likely not something that you should do much in React which means you will probably not use object much Empty interface, {and object ‘An empty interface, (} and object allrepresent "any non-nulish value"—not "an empty object" as you might think, Using these pes is 2 common source of misunderstanding and is nat recommended, Interface AnylooulLishvslue (J // equivalent to “type AnyonNllisielue = {}° or “type AnyonbulLishvalue = object 2 let value: arynonullistvalues 11 these are all fine, but mient not be expects value = Value = () => alert("f00")s value = 03 value = ( foo: “bee” 3: 11 these are errors value = undetined: value = o0115 Useful React Prop Type Examples Relevant for components that accept other React components as props. export declare interface AapProns { e ‘enideen?: React.ReactNade: / best, accepts everything Rea ‘hildrenElenent: React.25X.Elenert; // A single React elener= Styler: React.cSsPropercies; // to pass through style props Conchange?: React.FormeventHandler; // fore events! the generic parareter is the type of event.target {1 wore info: hetps://react-typescrigt-cheatsheet.netli¢y.apo/déocs/sevancea/patters_by_usecase/Aerappingnirroring props: Props & React. ConponentPropsuishouttef<"button">; // £0 inpersonate all the props of 2 button elenent and explicitly mi brops2: Props & React. ConponentPropsnishkefiyauttonksthforwardef9; // £9 Sepersanate all the props of Hybuttonforwardedtor — » > Small neact.neacttade edie case before React 18 > ReactSx.Element vs React ReactNode? More discussion: Wnere ResctNode doas not overlap with RexctJSK Element Something to add? File an issue, ‘Types or interfaces? You can use either Types or Interfaces to type Props and State 50 naturally the question arises ~ which do you use? Tuo Use Interface unl You Need Type - ot, More Advice Here's a helpful rule of thumb: + alvays.se snteréace for public APIs definition when authoring a ibrary oF rd party ambient type definitions, as this allows a consumer ‘o-extend them via declaration merging if some definitions are missing + consider using type for your React Component Props and Stat, for consistency and because itis more constrained. You can read more about the reasoning behind this rule of thumb in Interface vs Tyoe alias in TypeSeriot 27. -nps:fgthub.comtypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentref 18198 26106725, 00:37 GitHub - typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript ‘The TypeScript Handbook now also includes guidance on Differences Between Type Aliases and Interfaces ‘ Note: At scale, there are performance reasons ta prefer interfaces (se official Microsoft notes on this) ut take this witha grain of salt ‘Types are useful for union types (2.9. type MyType = Tyeek | Typed) whereas Interfaces are better for declaring dictionary shapes and then ‘nplonenting oF extensing them Useful table for Types ws Inerfaces Its a nuanced top, don't get too hung up on it Here's a handy table: Aspect Type Interface Can describe functions a Can describe constructors a ‘Can descrive tuples Interfaces can extend it Classes can extend it {Classes can implement it (Snplenexts ) Can intersect another one of is kind Can create a union with another one ofits kind ‘Can be used to create mapped types ‘Can be mapped over with mapped types a Expands in error messages and logs ° ‘Can be augmented a 98 9 a 9 a ‘canbe recursive > Ah tr some cases (source: Karol Majewski Something to add? Fle an issue. getDerivedStateFromProps Before you start using_setberivedstateFronProps, please go through the dacumentation and You Probably Don't Need Derived State. Derived State can be easly achieved using hooks which can also help set up memoization easly Here are afew ways in which you can annotate getDerivedstateFranProps 1. you have explicily typed your derived state and want to make sure that the return value from getDerivedstateFrenProps conforms toi lass Comp extends React.Conponentebrops, Stater { e stavie gevderivedsateFronPrope( Ds Partiatestate> | mull ¢ a > ? 2, When you want the function's etum value to determine your state. class Conp extends React. Componente e eturatypectypeor Conp["getoertvedstateFronmrops")> 4 Static gevDerivedstateFronPreps(oraps: Props) (2 } 43. When you want derived state with other state fields and memoization -nps:fgthub.comtypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentref 14198 26106725, 00:37 GitHub typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript type costonvalve = anys eo: sntertace Prope { proph: custonvalue; ? Interface befinedstate { otherstateField: string: ‘ype State = Defineestate & ReturnTypectypeor transformPropsTestate>; function transformPropsTestate(preps: Preps) ( return { savedProat: props.proah, // save for nenotzation eriveastate: props.prepA, % ? Class Conp extends React. PuneConponent { ‘onstructor(praps: Props) { surer(eraps);, this.state = ¢ + transtornPropsrestate(erops), » ) Statle getberivedstateFronProps(props: Props, state: state) { 34 GsEqal(orops.proph, seate.saveéPropt)) return null; rotuen eransforaPropstostate(props)s > : ‘ew in the TypeSerpt Playground Forms and Events If performance isnot an issue (and it usualy is), inlining handlers is easiest as you can just use type inference and contextual typing: mst al = ( @ onclicke<{event) => ( 7+ event wilt be corre » Pb » But ifyou need to define your event handler separately IDE tooling really comes in handy here, asthe @type definitions come with a wealth of 'yping. Type what you ae looking for and usualy the autocomplete will help you out. Here is what it looks like for an onchange fora form ‘type state = ¢ e u Class App extends React. CanporentePrope, State> { state <{ » (1 sping on RIGHT nar skce of = onchange = (e: React. FornEventchTMLEnpstélenant®): this.setstate({ text: e.currentTarget.value 295 i rencert) ( ratorn ( ‘ sas » ) ‘View in the TyoeScrpt Playground Instead of typing the arguments and return values with feact.Ferntvent©> and votd , you may altematively apply types tothe event handler itself (contributed by @ TomasHubelbavers -nps:fgthub.comtypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentref 18195 26106725, 00:37 GitHub - typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript 11 typing on LEFT hand side of = eo. lnchanges RenceChangetventdandlerchTaltnputelenent> = (@) => ‘this. setstate( (tert: e.currentTarget.value)) ? > Why two ways to do the same thing? ‘Typing onSubmit, with Uncontrolled components in a Form you don’ quite care about the type of the even, you can ust use React.syntnetieevent your target form has custom named inputs that you'd like to access, you can use a type assertion: fore e refo(forater) cnsuimita{(e: React. synthettetvert) => { evoreventDefault()s const tanget = e,target 2s typeof evtarget & { ferail: { value! string }: pacewords { valuet string 5 w Const epail = target.enaiL.valves // typeshecks const patmiord « torget.painord.values // typechecks! Mee » “lates esiapels sain ease input typespassword” nanes"passworé” /> sai “hnput ‘ype-"subait™ valves"Log in” /> roi “itor View in the TyoeScript Playground ‘Of course, you're making any sort of significant form, you should use Formik or React Hook Form, which are writen in TypeScript. List of event types Event Type Description Animationsvent 55 Animations Changefvent Changing the value of , element ClipboardEvent Using copy paste and cut events composiontven [Ns ths ocd fo the ver nec entering tex (eg depending on Browse and PC stu,» popup window ‘may appear with addtional characters if you eg. want to type Japanese on a US Keyboard) Dragkvent Drag and drop interaction with a pointer device fe, mouse) Focustvent Event that occurs when elements gets or loses focus. sorntvent Event that occurs whenever a form or form element gets/loses focus, frm element value is changed or the form is submited imvaldevent Fey ea ae Cc RR oe KeybosrdEvent User interaction withthe keyboard, Each avant dercrbes a single kay interaction, Inpatévert vent that occurs before the vale of changes. Mousefvent Events that occur due tothe user interacting witha pointing device (eg, mouse) -nps:fgthub.comtypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentref 16195 26106725, 00:37 GitHub - typescript choatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript Event Type Description f Events that occur due to user interaction with a variety pointing of devices such as mouse, pen/stylus, 2 touchscreen PointerEvent and which also supports multi-touch, Unless you develop for older browsers (E10 or Safari 12), pointer events are recommended. Extends UlEvent. Touchfvent Events that occur due tothe user interacting with a touch device, Extends UlEvent Transitiongvent C55 Transition, Not fully browser supported, tends UlEvent Ulevent Base Event for Mouse, Touch and Pointer events Wheelevent Scroling on a mouse whee! or similar input device. (Note: wheel. event should not be confused withthe scroll event) ‘SyntheticEvent The base event for all above events Should be used when unsure about event type Context Basic example Here's a basic example of creating a context containing the active theme Amport { crenteContent ) fron "reset"; e ‘ype Thenecontext Type = "Light" | "dark"; const Tanecontext = crescecontextTmeneContextType("1S8h0")5 ‘Wrap the components that ned the context with a context provider ssoort { usestate } from "react": e const Aap = () => ¢ ‘const (thene, setThene] = usestatecThanecontertType>(L4gnt")s return ( “Thenecontext-Provicer valuee(theme)> styconponent. > “i TmenecantextProviaer> Call usecontext to read and subscribe tothe context ingore { usecontext } from “react; @ const mycomonent = ‘const thene = useContext (TheeeContent); return 4 ‘Without default context value you don't have any meaningful default value, specify sult Inport { ereateContent } fron "eenet"s e Antertace Cunremtusercontexttyoe ( sernanet strings const CunnentUserContext = crestecontext (oul); const Ap = => e ‘onst [eurrentuser, setCurrentUser] = usestatecCurrentiserContextType>(¢ Usernane: “#iliptannergard", » return ( -nps:fgthub.comitypescrgt-cheatsheotsreact7tabsreadme-ov-fleoption-1-dom-olomentsef 17198 26106725, 00:37 GitHub - typescript cheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript -cunventsercontent. Provider value={currentUsen)> “tycanzonent > ‘const currentUser = usecontext(CurrentUserContext; return epoMane: (currentUser?.usernane) 7995 However, it would be preferable to not have to check for null since we know thatthe context won't be null. One way to do that isto provide a custom hook to use the context, where an error i thrown ifthe context is not provided: moore { createcontext } fon “react”; e sntortace Currentusercontexttype ? const CurrentuserContent = crestecontextcCurrentsercantentType | oul); canst securcentuser = Q) => { ‘const currentUserContext = vseContext(CurrentUsercontext); 46 (Vourrentusercontess) ( ‘hrow new Error( » > Using a euntime type check inthis ill hs the benefit of printing a clear error message in the console when a provider is not wrapping the components propetly, Now it's possible to acces= currentuser.vaernane without checking for ull ingore { usecontext } fron “react; e const Mycomponent = (09 ‘const currentUser = usecurrentUser()s return s ‘ype asersion a an serative Another way to aveld having to check for null isto use type assertion to tll TypeScript you know the contexts not st sport { wsecontext } fram “react; e const mycomponent =) ‘const currentUser = usecontext (Currentisercontext): return eppwane: (currentuser! usernane)

: Another option isto use an empty object as defout value and cast to the expected context type const CurrentuserContext = createcontext( e 85 CurrentusercontextType % You can also use non-null assertion to get the same resulk -nps:fgthub.comtypescrgt-cheatsheotsreact7tab=readme-ov-fleoption-1-dom-olomentref 18195 26106725, 00:37 GitHub -typeseriptcheatsheetsireact: Cheatsheets for experienced React developers goting started with TypeScript const CunnentUserContext = createContext(0W1LID5 e ‘when you don't know what to choose, prefer runtime checking and throwing over type asserting, forwardRet/ereatenet Check the Hooks section for useRer Angort { createhef, Purecanponent } from “react; e class CastbeneProvider extends PureComponent { private reotter = createtefaTMDivelenent>(); // Like this rengert) ( return «div rofafthis.roottaf)>{thts.props.chiléren)5 ) ? moore { foruardter, Reserhoce ) fron “resets e sntortace Props { ‘ype: “suonit™ | “buttons : fxsort type Ref = MTALBUttonELenent; export const Faneybutton = forwanctercRef, Props>((prans, ref) => ( “outton refefref} classtaner"MyClassNane” typer{orops.typ=)> “props. ctidren} ms > Side note: the ref you get from foruardket is mutable so you can assign to tif needed, you are grabbing the props of a component that forwards refs, use corponentProvshlthtet Generic forwardRets Read more context in htps/ettbloo,ewypescriptreact-generic-forward-refsl ‘option 1- Wrapper component type ClickableListeropsct> = { e tens: TO conselect: (Ktem: 1) => voser nner? React-RereATMUListELenent> | nuit; export function CLickableListct> (props: ClickableListPrepseT>) { return (