Why TypeScript and installation
This course assumes you already know basic JavaScript: variables, functions, arrays, objects and conditionals. If not, take the course 'JavaScript from scratch' first and come back. TypeScript is not a different language, it is JavaScript with an extra layer: a type system that checks your code before it runs. Every valid JavaScript program is also a valid TypeScript program, so you do not start from zero, you simply add guarantees.
The problem it solves
In JavaScript, type errors show up late, when the user is already using the application. You write user.nmae instead of user.name and nobody warns you: the result is undefined and the failure appears far from where the mistake was. You call a function with the arguments in the wrong order, or add a number to a string, and the program carries on with an absurd result. TypeScript moves those discoveries to the moment you write the code: the editor underlines the error in red before you even save the file.
- It catches errors before the program runs.
- It makes editor autocompletion precise and useful.
- It works as documentation that never goes stale, because the compiler checks it.
- It makes refactoring easier: if you change a function, the compiler shows every broken place.
- It compiles to plain JavaScript, which runs in browsers and in Node.js.
One key idea: types only exist during development. When you compile, TypeScript erases all annotations and produces clean JavaScript. That is why types cost nothing at runtime, but also why they do not protect you from data that arrives from outside, such as an API response. We will cover that in week 8.
Setting up the environment
You need Node.js 22 or newer and an editor; Visual Studio Code already includes TypeScript support. Check your Node version with node --version. Then we create a working folder, start a project and install TypeScript as a development dependency, so that each project pins its own compiler version.
node --version
mkdir ts-course
cd ts-course
npm init -y
npm install --save-dev typescript tsx
npx tsc --versionWe install two tools. typescript brings tsc, the compiler that checks types and generates JavaScript. tsx is a runner that executes .ts files directly, very handy for practice. Careful: tsx does not check types, it just ignores them and runs the code. To find type errors you will always use tsc, and it is worth remembering that from day one.
// hello.ts
function greet(name: string): string {
return 'Hello, ' + name + '!';
}
console.log(greet('TypeScript'));
// greet(42); // error: Argument of type 'number' is not assignable to parameter of type 'string'اختبر ما تعلمته
السؤال 1 من 1What does TypeScript do with type annotations when compiling?
✎ ملاحظاتي
محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف