What is TypeScript?
TypeScript Origins
JavaScript, to which TypeScript compiles, is considered a programming lingua franca of the modern world. JavaScript was primarily dedicated to elementary browser document operations. Now, it underpins complex client- and server-side applications.
Maybe due to its intricate evolution or maybe due to architectural decisions JavaScript does not feature a strong typing solution for its values. TypeScript began its life as a Microsoft endeavor to address that issue but it became a powerful system of static checking of JavaScript code and even enhancing it with some runtime elements.
One of the main architects of TypeScript was Anders Hejlsberg. The first public version of TypeScript 0.8
appeared in 2012.
TypeScript as Strict Superset of JavaScript
From a syntactical perspective, TypeScript is a strict superset of JavaScript, meaning that any JavaScript code is a valid TypeScript code but not all TypeScript code is a valid JavaScript code.
// Valid TypeScript and valid JavaScript code
var foo = 'bar'
function logBaz(baz) {
console.log(baz)
}
// Valid Typescript but invalid JavaScript code
var foo: string = 'bar'
function logBaz(baz: any) {
console.log(baz)
}
Type annotations present in the TypeScript code are not allowed in JavaScript code.
Static Code Checking in TypeScript
One of the key concepts to grasp about TypeScript is that its code checking is static which means it takes place before run-time.
Generally, TypeScript code cannot be run by JavaScript runtime environments such as browsers or Node servers. It first needs to be compiled into pure JavaScript. During the JavaScript runtime, no code checking capabilities of TypeScript are present anymore.
TypeScript provides static JavaScript code checking within the following areas:
Structural Type Checking in TypeScript
Another key concept to grasp about TypeScript is that its type checking of non-primitive values is structural, and not nominal.
// In TypScript classes are both values and types
class Dog {
walk() { console.log('walking') }
}
class Cat {
walk() { console.log('walking') }
}
const Pluto: Dog = new Cat() // Allowed from TypeScript perspective.
Non-Static JavaScript Extensions in TypeScript
As already noted, no TypeScript code checking capabilities are present after it is compiled to JavaScript.
This does not mean that all TypeScript code is removed from the compiled JavaScript code. Some TypeScript elements extend JavaScript with some additional capabilities. However, those elements, after compilation, are still expressed as pure JavaScript code.
The TypeScript elements that non-statically extend JavaScript are for example:
-
decorators, and