Skip to content

Instantly share code, notes, and snippets.

@kas-elvirov
Forked from juhaelee/react-typescript.md
Created August 17, 2018 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kas-elvirov/f84855a685139f99e6d0186e542c5cf0 to your computer and use it in GitHub Desktop.
Save kas-elvirov/f84855a685139f99e6d0186e542c5cf0 to your computer and use it in GitHub Desktop.
React + Typescript Cheatsheet

React + Typescript Cheatsheet

Setup

If you use atom... download & install the following packages:

What are Typescript type definition files? (*.d.ts)

You may see a folder called typings with a lot of files that follow the pattern *.d.ts. These are type definition files. Type definition files are used to declare the interfaces of public API of third party libraries like jQuery or React. That way you don't have to create all the typings for third party libraries!

How do you create a React component with Typescript?

  • Create a file using the .tsx extention

  • Declare the interface for any props that that the React Component uses

interface TodoProps {
    todo: string
    status: string
}
  • Declare the interface for any state that exists within the React component
interface TodoState {
    isEditing?: boolean
    // Make all state optional! See Hack below
}

Hack: For now make every key in state optional or else Typescript with throw an error

  • Create a React component using the interfaces you created
class TodoComponent extends React.Component<TodoProps, TodoState> {
    constructor(props: TodoProps) {
        super(props)
        this.state = { ... } // initial state
    }
    ... // public + react methods
}

Misc

refs

In order for Typescript to be happy, use refs inside the class like so:

class Cat extends <CatProps, {}> { // no state
  refs: {
    [key: string]: (Element)
    litterBox: (HTMLInputElement) // !important
  }
  constructor(props: CatProps){ ... } // constructor
  render() {
    return (
      <div ref="litterBox">
        litter
      </div>
    )
  }
}

Glossary

Interface

A collection of types that describes the shape that a value must have

interface CatValue {
  name: string
  age: number
}

function petCat(cat: CatValue) {
  console.log(cat.name)
}

let myCat = { name: 'Whiskers', age: 4 }
petCat(myCat) // 'Whiskers'

PROTIP: use ? for optional values

interface CatValue {
  name: string
  age: number
  favoriteFish?: string // optional
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment