TypeScript · Lesson 1 of 4
Why TypeScript
Set up TypeScript and meet basic type annotations and inference.
- Beginner
- 12 min read
- 3 objectives
What you will learn
- Install and run tsc
- Annotate variables and functions
- Read a type error
TypeScript is JavaScript with a type system. You add annotations that describe the shape of your data, and the compiler checks them before the code runs, catching typos, missing fields and wrong arguments while you type. It compiles to plain JavaScript that runs anywhere.
Setup
mkdir ts-demo && cd ts-demo
npm init -y
npm install --save-dev typescript tsx
npx tsc --init # creates tsconfig.json// hello.ts
const name: string = "stackcone";
console.log(`Hello, ${name}`);npx tsx hello.ts # run directly
npx tsc # or compile to JavaScriptAnnotations
let count: number = 3;
let title: string = "TS";
let done: boolean = false;
let tags: string[] = ["a", "b"];
let pair: [string, number] = ["age", 36]; // tuple
function add(a: number, b: number): number {
return a + b;
}Type inference
You do not need to annotate everything. TypeScript infers types from values, so let n = 5 is already a number. Annotate function parameters and public return types; let inference handle local variables.
Reading an error
add(1, "2");Output
error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
The compiler points to the exact place and explains the mismatch. In plain JavaScript this would have silently produced "12" at runtime.
any, unknown and never
anyturns off type checking for a value. Avoid it; it hides bugs.unknownis the safe alternative: you must check the type before using the value.nevermarks code that cannot happen, such as a function that always throws.
function parse(input: unknown): number {
if (typeof input === "number") return input;
if (typeof input === "string") return Number(input);
throw new Error("cannot parse");
}// Write your solution here
