DEV Community

miku86
miku86

Posted on

TypeScript: Basic Workflow

Intro

In this article, we will have a look at the basic workflow of writing TypeScript.


Overview

3 Steps Are Necessary:

  1. Write TypeScript Code
  2. Compile It To JavaScript
  3. 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);
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Compile it again, until no errors are left.


3. Run The JavaScript Code

node index.js
thirty-one
thirty-one
Enter fullscreen mode Exit fullscreen mode

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)