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
-
--save-dev
is the same as-D
-
npm
is Node Package Manager
TypeScript config
Create a new TypeScript config with:"
$ npx tsc --init
-
npx
is Node Package e*X*ecutor, and part ofnpm
: 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");
-
string
is the type ofperson
-
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
And then run it:
$ node greeting.js
Hello John!
TypeScript & React
Install create-react-app
and create a new React app with TypeScript support with:
$ npx create-react-app my-app --template typescript
-
npx
here is installcreate-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;
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;
Start the Node server:
npm start
Top comments (0)