Intro
In this article, we will have a look at the basic workflow of writing TypeScript.
Overview
3 Steps Are Necessary:
- Write TypeScript Code
- Compile It To JavaScript
- Run The JavaScript Code
1. Write TypeScript Code
// explicit typing
let myAge: string = 'thirty'; // set it explicitly to a string
myAge = 'thirty-one'; // that works
// implicit typing / type inference
let yourAge = 30; // typescript infers the type as number
yourAge = myAge; // trying to set it to a string, does not work
console.log(myAge);
console.log(yourAge);
2. Compile It To JavaScript
tsc index.ts // tries to create a file index.js from index.ts
index.ts:7:1 - error TS2322: Type 'string' is not assignable to type 'number'.
7 yourAge = myAge; // trying to set it to a string, does not work
Found 1 error.
Because there's an error, you have to fix the code.
Fix it
// explicit typing
let myAge: string = 'thirty'; // set it explicitly to a string
myAge = 'thirty-one'; // that works
// fix by using explicit typing
let yourAge: number | string = 30; // set it explicitly to a number or a string
yourAge = myAge; // trying to set it to a string, works
console.log(myAge);
console.log(yourAge);
Compile it again, until no errors are left.
3. Run The JavaScript Code
node index.js
thirty-one
thirty-one
Next Part
We will learn how to configure the TypeScript
compiler.
Further Reading
TypeScript Homepage
TypeScript Wikipedia
TypeScript in 5 minutes
Basic Types
Various Samples
Top comments (0)