
TypeScript
Introduction
Welcome to the world of TypeScript, a powerful superset of JavaScript that has been making waves in the development community. Whether you're a beginner taking your first steps into programming or an intermediate developer looking to expand your skill set, this article is your gateway to understanding and harnessing the capabilities of TypeScript.
What will be present:
- Typescript description and history
- Set up
- Introductory programs with build/run instruction
- Comparasion with others language
- Complex examples and group project
Brief History
- First announced by Microsoft in October 2012, with Anders Hejlsberg. He was the original author of Turbo Pascal and the chief architect of Delphi. He currently works for Microsoft as the lead architect of C# and core developer on TypeScript.
- TypeScript was to address the shortcomings after JavaScript, particularly in large-scale applications. The thing is JavaScript is a loosely typed and dynamiic language. JavaScript has grown exponentially but also prone to runtime errors due to its lack of type checking, especially in building huge application.
- TypeScript 1.0 which was released at the Build 2014 with a new compiler. The team claims would bring five times gains in performance. As round a same time, the source code was shifted to Github which was originally hosted by CodePlex.
- TypeScript goal is to be a static type checker for JavaScript - in other words, a toll that runs before your code runs (static) and ensures that the types of the program are correct (type-checked)
Features
- OOP: based on the concept of objects, which can contain data and code: data in the form of fields, and code in the form of procedures. Methods are attached to them and can access and modify the object's data fields.
- TypeScript is a subset of JavaScript. all the libraries and existing JavaScript code are valid TypeScript code as well.
- Code Organization: TypeScript provides built-in support for modules and namespaces to organize code better.Modules allow for encapsulation of code within separate files, making it easier to manage and maintain large codebases.
// greeting.ts: export function greet(name: string): string { // Export a function from a module return `Hello, ${name}!`; } // app.ts: import { greet } from "./greeting"; // Import from a module console.log(greet("John")); // Output: Hello, John!
- TypeScript has the feature of strong static typing which comes through TLS(TypeScript language service). It allows developers to specify the types of variables, function parameters, and return values, catching type-related error at compile time.
TypeScript Type

TypeScript Tupel
Tuple is similar to array but their elements can have different types. All the elements types must be declared in order in the declaration.
Example: const t2:[string, number, boolean] = ['Manu', 100, true];
TypeScript Never
It represents the type of values that never occur. A function that returns nothing can have return type as void. However a function that never returns (or always throws) can have return type as never.
Example: let bar: never = (() => { throw new Error('Error!') })();
TypeScript typeof operator
TypeScript typeof operator is used to get the type of a variable.For example, TypeScript knows that only a string value will have a typeof value "string": Example:
let strOrNum: string | boolean ; if(typeof strOrNum === "string") { strOrNum = 'Hello'; } if(typeof strOrNum === "boolean") { strOrNum = true; }
Type Aliases
Instead of using object type or union type, it is common to want to use the same type more than once and refer it to a single name Example:
type Point = { x: number; y: number; }; // Exactly the same as the earlier example function printCoord(pt: Point) { console.log("The coordinate's x value is " + pt.x); console.log("The coordinate's y value is " + pt.y); } printCoord({ x: 100, y: 100 });
Optional Properties
Object types can also specify that some or all of their properties are optional. To do this, add a ? after the property name: Example:
function printName(obj: { first: string; last?: string }) { // ... } // Both OK printName({ first: "Bob" }); printName({ first: "Alice", last: "Alisson" });
TypeScript Classes
Using class keyword:class ClassName{ //constructor; //field; //method;
class Box { legth: number; width: number; constructor(legth: number, width: number) { this.legth = legth; this.width = width; } add(box: Box) { return new Box(this.legth + box.legth, this.width + box.width); } }
Setup
npm
To get started, you'll need Node.js, which includes npm (Node Package Manager). To initialize a Node.js project, run the following command in your project root directory:
npm init -y
This creates a package.json
file to manage your project's dependencies and share it with others.
TypeScript Installation
TypeScript can be installed in two ways: locally or globally.
Locally (recommended)
npm install typescript --save-dev
This command installs TypeScript in the current project directory as a development dependency. The TypeScript compiler (tsc
) can be accessed using npm scripts defined in your package.json
file.
Local installation ensures that everyone working on the project is using the same version of TypeScript.
Globally
npm install -g typescript
This command installs TypeScript globally on your system. This means you can access the TypeScript compiler (tsc
) from any directory on your system.
Global installation could lead to versioning issues if different projects rely on different versions of TypeScript.
tsconfig
A tsconfig.json
file provides configuration options for the TypeScript compiler. It allows you to specify things like the target JavaScript version, module system, and output directory. Having a tsconfig.json
file ensures that your TypeScript code is compiled consistently across different environments.
The following is an example of a basic tsconfig.json
file:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "./dist"
}
}
Alternatively, you can generate a tsconfig.json
file with all possible compiler options commented out, by running the tsc --init
command. Since this generated file contains a lot of information though, it can be overwhelming for beginners.
Writing and Compiling TypeScript
After setting up TypeScript for your project, you can now start writing and compiling TypeScript code to enjoy the benefits of type checking and static analysis. For this demo, lets write a basic hello-world program.
- Create a new file with a
.ts
extension (e.g.hello.ts
)
- Write the following hello-world program
let message: string = 'Hello World!'; console.log(message);
- Navigate to the directory where
hello.ts
is located in your terminal
- Use the
tsc
compiler to compile the TypeScript file into JavaScriptnpx tsc hello.ts
- Open
hello.js
. Notice how it doesn't look very different fromhello.ts
var message = 'Hello World!'; console.log(message);
- Run the compiled JavaScript code
node hello.js
TypeScript v.s. JavaScript
TypeScript v.s. Other Languages
Feature | TypeScript | Python | PHP | C |
---|---|---|---|---|
Type System | Static | Dynamic | Dynamic | Static |
Translator | Transpiler (tsc) to JavaScript | Interpreter | Interpreter | Compiler |
Binding | Early binding (static binding) | Late binding (dynamic binding) | Late binding (dynamic binding) | Early binding (static binding) |
Visibility | Public, private, protected | Public, private, protected | Public, private, protected | Public, private, static |
Scoping | Block-scoped and function-scoped | Block-scoped and function-scoped | Function-scoped | Block-scoped and function-scoped |
Lifetime Management | Automatic garbage collection | Automatic garbage collection | Automatic garbage collection | Manual memory management |
Interfaces | Supports interfaces to define the structure of objects | Does not have built-in support for interfaces, but can be emulated using abstract classes | Does not have built-in support for interfaces, but can be emulated using abstract classes | Does not have built-in support for interfaces |
Generics | Supports generics to write reusable code that works with different data types | Does not have built-in support for generics | Does not have built-in support for generics | Does not have built-in support for generics |
Parameter-Passing | Supports both pass-by-value and pass-by-reference parameter passing | Supports pass-by-object parameter passing, which is similar to pass-by-reference | Supports pass-by-reference parameter passing | Supports pass-by-value parameter passing |
Metapogramming | Supports decorators and reflection | Strong support with decorators, metaclasses, and dynamic manipulation | Limited support compared to Python, includes reflection and dynamic creation | Minimal support; lacks reflection and runtime code generation |
Complex example
Account.java vs Account.ts




