DEV Community

Cover image for Getting started with TypeScript & React
Johnß
Johnß

Posted on

Getting started with TypeScript & React

A quick and dirty guide for myself to get started with TypeScript. Based on the notes from Simon Willison.

Install

With npm installed, install TypeScript into the dev-dependencies with:

$ npm install --save-dev typescript
Enter fullscreen mode Exit fullscreen mode
  1. --save-dev is the same as -D
  2. npm is Node Package Manager

TypeScript config

Create a new TypeScript config with:"

$ npx tsc --init
Enter fullscreen mode Exit fullscreen mode
  1. npx is Node Package e*X*ecutor, and part of npm: it allows you to run Node “scripts” from a project rather than having to install them globally or to the PATH

Make a TypeScript file, greeting.ts:

const greeting = (person: string): void => {
  console.log(`Hello ${person}!`);
};
greeting("John");
Enter fullscreen mode Exit fullscreen mode
  1. string is the type of person
  2. void is a special type to denote that this function doesn't return anything

Compile it with tsc, the Type*Script **C*ompiler:

$ npx tsc
Enter fullscreen mode Exit fullscreen mode

And then run it:

$ node greeting.js
Hello John!
Enter fullscreen mode Exit fullscreen mode

TypeScript & React

Install create-react-app and create a new React app with TypeScript support with:

$ npx create-react-app my-app --template typescript
Enter fullscreen mode Exit fullscreen mode
  1. npx here is install create-react-app before executing it

A simple TSX component

A straight forward React component, Greeting.tsx showing TypeScript with JSX.

import React from "react";
import { useState } from "react";

function Greeting(props: { name: string }) {
  const [value, setValue] = useState(props.name);

  const onChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
    setValue(event.target.value);
  };

  return (
    <>
      <input value={value} onChange={onChange} />
      <h1>Hello {value}!</h1>
    </>
  );
}

export default Greeting;
Enter fullscreen mode Exit fullscreen mode

Add it to the App.tsx:

import React from "react";

import Greeting from "./components/Greeting";

function App() {
  return (
    <div>
      <Greeting name="John" />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Start the Node server:

npm start
Enter fullscreen mode Exit fullscreen mode

Top comments (0)