TypeScript for Beginners: Setup and Your First Types
Introduction
TypeScript is JavaScript with static types. You write TypeScript, the compiler checks it for mistakes, and it outputs plain JavaScript that runs anywhere JavaScript does. This tutorial gets you set up and shows the compiler catching a real error.
Prerequisites
- Node.js 18 or newer installed
- Basic JavaScript knowledge
Step-by-Step Guide
Step 1: Create a project and install TypeScript
Install the compiler as a development dependency in a new project.
mkdir ts-demo
cd ts-demo
npm init -y
npm install --save-dev typescriptStep 2: Generate a tsconfig.json
The tsconfig.json file tells the compiler how to check and emit your code. The init command creates one with sensible defaults and comments explaining each option.
npx tsc --initStep 3: Write typed code
Create hello.ts. Annotate parameters and return values with types after a colon.
function greet(name: string): string {
return "Hello, " + name;
}
console.log(greet("Ava"));Step 4: Compile and run
tsc compiles hello.ts into hello.js, which you run with Node. To run TypeScript directly while experimenting, you can also use npx tsx hello.ts.
npx tsc
node hello.jsStep 5: See the compiler catch a mistake
Passing the wrong type is now an error at compile time, not a surprise at runtime.
greet(42);
// Error: Argument of type 'number' is not assignable to parameter of type 'string'.FAQs
- Does TypeScript run in the browser?
- Browsers run JavaScript, not TypeScript. The compiler (or a build tool) converts your TypeScript to JavaScript first.
- Do I have to rewrite my JavaScript to use TypeScript?
- No. TypeScript is a superset of JavaScript, so valid JavaScript is valid TypeScript. You can adopt types gradually, file by file.
Summary
Install typescript, run tsc --init, add types to your code, and compile. The payoff is that many bugs surface in your editor and build instead of in production.
Comments
Log in or create a free account to join the discussion.