Why TypeScript
Set up TypeScript and meet basic type annotations and inference.
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.
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 JavaScriptlet 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.
add(1, "2");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");
}Types exist only at compile time. They are erased in the output, so they cannot check data arriving from an API at runtime; you will handle that in a later lesson.
Try it yourself
Write a function average(nums: number[]): number and confirm the compiler rejects average("1,2,3").
Show solution
function average(nums: number[]): number {
return nums.reduce((a, b) => a + b, 0) / nums.length;
}
average([1, 2, 3]); // OK: 2
// average("1,2,3"); // Error: string is not assignable to number[]