“a layer on top” of JavaScript
ES6 : Version 6 of ECMA Script programming language
TSC : TypeScript Compiler
transpiler
Support modern JavaScript features
Static type-checking
Object-Oriented language
JavaScript language (not the runtime) is standardized through the ECMAScript standards.
Not All browsers & JavaScript runtimes support all features
TypeScript allows use many of the latest ECMAScript features and translates them to older ECMAScript targets of your choosing
Option | Type | Default | Description |
---|---|---|---|
--target -t |
string | "ES3" | Specify ECMAScript target version: ► "ES3" (default) ► "ES5" ► "ES6"/"ES2015" ► "ES2016" ► "ES2017" ► "ES2018" ► "ES2019" ► "ES2020" ► "ESNext" Note: "ESNext" targets latest supported ES proposed features. |
Compiler Option
JavaScript is dynamically typed
JavaScript does not know what type a variable is until it is actually instantiated at run-time
TypeScript adds type support to JavaScript
JavaScript | TypeScript |
---|---|
var x = "hello" | var x : string = "hello" |
Example
Four main principles to Object Oriented Programming:
TypeScript can implement all four of them with its smaller and cleaner syntax.
Codebase is huge, and more than one person works on the project
A type system can help to avoid a lot of common errors
The TypeScript transpiler reveals the most obvious mistakes
Transpile ES6 code into ES5 using the TypeScript transpiler
TypeScript has some cool features that are not in ES6 such as enums and the ability to initialize member variables in a constructor.
In inheritance, it useful to have the public, private, protected, and abstract keywords in classes.
TypeScript has them and ES6 doesn’t.
JavaScript code, we had a lot of type checks
Skip a lot of unnecessary runtime type checking.
Even a small error could be literally fatal if it wasn’t dealt with properly. So a lot of functions had statements like:
if(typeof name !== ‘string) throw ‘Name should be string’
TYPESCRIPT | JAVASCRIPT | |
---|---|---|
Type | Strongly type object-oriented compile language |
Lightweight, interpreted programming language |
Language | Object-oriented programming language | Scripting language |
File Extension. | . ts, .tsx | .js |
TYPESCRIPT | JAVASCRIPT | |
---|---|---|
Preference to choose |
> An object-oriented language > Code more consistency, clean, simple and reusable. > Better to use typescript for developing large projects. |
> Preferable to use in relatively small coding projects. |
Example |
|
const message:string =
'Hello Malaysia'
console.log(message)
var message = 'Hello Malaysia';
console.log(message);
PROS | CONS |
---|---|
Static Typing | Required compilation |
Avoid Common Errors | False sense of security |
Compatible with all JavaScript libraries | Learning Curve |
Refactoring Tools | |
Reduce the Amount of Unit Tests |