Measures Concepts
GitHub icon

TypeScript

TypeScript - Programming language

< >

TypeScript is an open source programming language created in 2012 by Anders Hejlsberg.

Source code:
git clone https://github.com/microsoft/TypeScript
#31on PLDB 12Years Old 3mRepos

Try now: Web ยท Riju ยท TIO

TypeScript is a free and open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language. Anders Hejlsberg, lead architect of C# and creator of Delphi and Turbo Pascal, has worked on the development of TypeScript. Read more on Wikipedia...


Example from Riju:
console.log("Hello, world!");
Example from hello-world:
console.log("Hello World");
// Hello world in TypeScript alert('Hello world!');
Example from Linguist:
console.log("Hello, World!");
Example from Wikipedia:
class Person { private name: string; private age: number; private salary: number; constructor(name: string, age: number, salary: number) { this.name = name; this.age = age; this.salary = salary; } toString(): string { return `${this.name} (${this.age}) (${this.salary})`; // As of version 1.4 } }

Language features

Feature Supported Token Example
MultiLine Comments โœ“ /* */
/* A comment
*/
Comments โœ“
// A comment
Algebraic Data Type โœ“
declare type numOrString = string | number
Line Comments โœ“ //
// A comment
Union Types โœ“
declare type numOrString = string | number
Single-Type Arrays โœ“
const scores: int[]
Type Inference โœ“
Strings โœ“ "
"hello world"
Type Parameters โœ“
function identity(arg: T): T {
   return arg;
}
Static Typing โœ“
Inheritance โœ“
class B {}
class A extends B {}
Print() Debugging โœ“ console.log
console.log("Hi")
Namespaces โœ“
// Typescript even supports splitting namespaces across multiple files:
// Validation.ts
namespace Validation {
    export interface StringValidator {
        isAcceptable(s: string): boolean;
    }
}
// LettersOnlyValidator.ts
/// 
namespace Validation {
    const lettersRegexp = /^[A-Za-z]+$/;
    export class LettersOnlyValidator implements StringValidator {
        isAcceptable(s: string) {
            return lettersRegexp.test(s);
        }
    }
}
Mixins โœ“
// https://www.typescriptlang.org/docs/handbook/mixins.html
class SmartObject implements Disposable, Activatable {
}
// Note: still need to do some runtime ops to make that work.
Interfaces โœ“
// https://www.typescriptlang.org/docs/handbook/interfaces.html
interface SquareConfig {
   color?: string;
   width?: number;
}
File Imports โœ“
import { ZipCodeValidator } from "./ZipCodeValidator";
/// 
/// 
import moo = module('moo');
/// 
Type Casting โœ“
something;
Classes โœ“
class Person {}
Booleans โœ“
const result = true
Generics โœ“
function identity(arg: T): T {
   return arg;
}
Abstract Types โœ“
abstract class Animal {}
class Dog extends Animal
Access Modifiers โœ“
class Person {
  private _age = 2
  public get age() {
    return _age
  }
  protected year = 1990
}
Static Methods โœ“
class Person {
  static sayHi() {
    console.log("Hello world")
  }
}
Enums โœ“
enum Direction {
 Up,
 Down
}
Scientific Notation โœ“
Binary Literals โœ“
// 0[bB][01]+n?
0b100110100000110011110010010
Floats โœ“
// (\.[0-9]+|[0-9]+\.[0-9]*|[0-9]+)([eE][-+]?[0-9]+)?
80766866.0
Hexadecimals โœ“
// 0[xX][0-9a-fA-F]+n?
0x4D06792
Octals โœ“
// 0[oO]?[0-7]+n?
0o464063622
Sets โœ“
set = new Set()
set.add("foo")
Function Composition โœ“
function o(f, g) {
   return function(x) {
       return f(g(x));
   }
}
Destructuring โœ“
const o = {p: 42, q: true};
const {p, q} = o;
Default Parameters Pattern โœ“
function multiply(a, b = 1) {
 return a * b;
}
Increment and decrement operators โœ“
let i = 0
i++
i--
Methods โœ“
class Person {
 method1() {}
 method2() {}
}
Functions โœ“
function helloWorld() {console.log("hi")}
Case Sensitivity โœ“
Zero-based numbering โœ“
While Loops โœ“
let times = 10
while (times) {times--}
console.log("done")
Ternary operators โœ“
let i = true ? 1 : 0
Switch Statements โœ“
var animal = "dog"
switch (animal) {
 case "dog": console.log("yay"); break;
 case "cat": console.log("oh"); break;
}
Letter-first Identifiers โœ“
References โœ“
Operators โœ“
1 + 1
Multiline Strings โœ“
const lines = `one
two`
Anonymous Functions โœ“
(() => console.log("hello world"))()
Infix Notation โœ“
const six = 2 + 2 + 2
Implicit Type Casting โœ“
console.log("hello " + 2)
Assignment โœ“
var name = "John"
Directives โœ“
"use strict";
"use asm";
Generators โœ“
function* fibonacci(limit) {
    let [prev, curr] = [0, 1];
    while (!limit || curr <= limit) {
        yield curr;
        [prev, curr] = [curr, prev + curr];
    }
}
// bounded by upper limit 10
for (let n of fibonacci(10)) {
    console.log(n);
}
// generator without an upper bound limit
for (let n of fibonacci()) {
    console.log(n);
    if (n > 10000) break;
}
// manually iterating
let fibGen = fibonacci();
console.log(fibGen.next().value); // 1
console.log(fibGen.next().value); // 1
console.log(fibGen.next().value); // 2
console.log(fibGen.next().value); // 3
console.log(fibGen.next().value); // 5
console.log(fibGen.next().value); // 8
// picks up from where you stopped
for (let n of fibGen) {
    console.log(n);
    if (n > 10000) break;
}
Garbage Collection โœ“
First-Class Functions โœ“
[2.0,1.1].map(Math.round)
Exceptions โœ“
try {
 undefinedFn()
} catch (err) {
 console.log(err)
}
hasDynamicTyping โœ“
Constants โœ“
const one = 1
Constructors โœ“
class Person {
 constructor(name) {
   this._name = name
 }
}
new Person("Jane")
Labels โœ“
main:
console.log("pldb")
Conditionals โœ“
if (true)
 console.log("hi!")
Method Chaining โœ“
"hello world".toString().substr(0, 1).length
Magic Getters and Setters โœ“
// Can be implemented in ES6 using proxies:
"use strict";
if (typeof Proxy == "undefined") {
    throw new Error("This browser doesn't support Proxy");
}
let original = {
    "foo": "bar"
};
let proxy = new Proxy(original, {
    get(target, name, receiver) {
        let rv = Reflect.get(target, name, receiver);
        if (typeof rv === "string") {
            rv = rv.toUpperCase();
        }
        return rv;
      }
});
console.log(`original.foo = ${original.foo}`); // "original.foo = bar"
console.log(`proxy.foo = ${proxy.foo}`);       // "proxy.foo = BAR"
Dynamic Properties โœ“
class Person {}
const person = new Person()
person.age = 50
Source Maps โœ“
{
 version: 3,
 file: 'min.js',
 names: ['bar', 'baz', 'n'],
 sources: ['one.js', 'two.js'],
 sourceRoot: 'http://example.com/www/js/',
 mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
};
Bitwise Operators โœ“
var x = 5 & 1;
Single Dispatch โœ“
Polymorphism โœ“
"a" + "b"; 1 + 2
Merges Whitespace โœ“
Lists โœ“
const list = [1,2,3]
Integers โœ“
80766866
Breakpoints โœ“
if (false)
  debugger
Partial Application โœ“
const addNumbers = (num1, num2) => num1 + num2
const add5 = num => addNumbers(10, num)
Map Functions โœ“
[1,2.1].map(Math.round)
Binary Operators โœ“
1 + 1
Async Await โœ“
async doSomething => await somethingElse()
Expressions โœ“
1 + 1
Regular Expression Syntax Sugar โœ“
console.log("Hello World".match(/\w/))
Statements โœ“
let x = 3;
hasExports โœ“
export function myFunction() {
}
hasSymbols โœ“
// A symbol is a unique and immutable primitive value, often used as a unique key for object properties
pldb = Symbol()
Case Insensitive Identifiers X
Semantic Indentation X
Operator Overloading X
Multiple Inheritance X
Function Overloading X
Macros X
Processor Registers X
Multiple Dispatch X
Pointers X
Variable Substitution Syntax X
S-Expressions X

View source

- Build the next great programming language ยท Search ยท Add Language ยท Features ยท Creators ยท Resources ยท About ยท Blog ยท Acknowledgements ยท Queries ยท Stats ยท Sponsor ยท Day 605 ยท feedback@pldb.io ยท Logout