2014-08-14 14:12:50 +04:00
|
|
|
---
|
|
|
|
language: TypeScript
|
|
|
|
contributors:
|
2014-09-01 12:51:43 +04:00
|
|
|
- ["Philippe Vlérick", "https://github.com/pvlerick"]
|
2022-08-08 07:02:53 +03:00
|
|
|
- ["Kiwimoe", "https://github.com/kiwimoe"]
|
2014-08-27 18:14:57 +04:00
|
|
|
filename: learntypescript.ts
|
2014-08-14 14:12:50 +04:00
|
|
|
---
|
|
|
|
|
2018-10-30 20:40:01 +03:00
|
|
|
TypeScript is a language that aims at easing development of large scale
|
|
|
|
applications written in JavaScript. TypeScript adds common concepts such as
|
|
|
|
classes, modules, interfaces, generics and (optional) static typing to
|
|
|
|
JavaScript. It is a superset of JavaScript: all JavaScript code is valid
|
|
|
|
TypeScript code so it can be added seamlessly to any project. The TypeScript
|
|
|
|
compiler emits JavaScript.
|
2014-08-14 14:12:50 +04:00
|
|
|
|
2018-10-30 20:40:01 +03:00
|
|
|
This article will focus only on TypeScript extra syntax, as opposed to
|
|
|
|
[JavaScript](/docs/javascript).
|
2014-08-14 14:12:50 +04:00
|
|
|
|
2018-10-30 20:40:01 +03:00
|
|
|
To test TypeScript's compiler, head to the
|
2019-11-04 23:11:16 +03:00
|
|
|
[Playground](https://www.typescriptlang.org/play) where you will be able
|
2018-10-30 20:40:01 +03:00
|
|
|
to type code, have auto completion and directly see the emitted JavaScript.
|
2014-08-14 15:34:41 +04:00
|
|
|
|
2016-11-20 22:31:22 +03:00
|
|
|
```ts
|
2015-03-10 23:09:35 +03:00
|
|
|
// There are 3 basic types in TypeScript
|
2017-05-25 18:35:08 +03:00
|
|
|
let isDone: boolean = false;
|
|
|
|
let lines: number = 42;
|
|
|
|
let name: string = "Anders";
|
|
|
|
|
2018-10-30 20:40:01 +03:00
|
|
|
// But you can omit the type annotation if the variables are derived
|
|
|
|
// from explicit literals
|
2017-05-25 18:35:08 +03:00
|
|
|
let isDone = false;
|
|
|
|
let lines = 42;
|
|
|
|
let name = "Anders";
|
2014-08-14 14:12:50 +04:00
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// When it's impossible to know, there is the "Any" type
|
2017-05-25 18:35:08 +03:00
|
|
|
let notSure: any = 4;
|
2014-08-14 14:12:50 +04:00
|
|
|
notSure = "maybe a string instead";
|
|
|
|
notSure = false; // okay, definitely a boolean
|
|
|
|
|
2018-01-25 22:56:33 +03:00
|
|
|
// Use const keyword for constants
|
2017-05-25 18:35:08 +03:00
|
|
|
const numLivesForCat = 9;
|
|
|
|
numLivesForCat = 1; // Error
|
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// For collections, there are typed arrays and generic arrays
|
2017-05-25 18:35:08 +03:00
|
|
|
let list: number[] = [1, 2, 3];
|
2015-03-10 23:09:35 +03:00
|
|
|
// Alternatively, using the generic array type
|
2017-05-25 18:35:08 +03:00
|
|
|
let list: Array<number> = [1, 2, 3];
|
2014-08-14 14:12:50 +04:00
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// For enumerations:
|
2017-05-25 18:35:08 +03:00
|
|
|
enum Color { Red, Green, Blue };
|
|
|
|
let c: Color = Color.Green;
|
2021-11-09 01:36:40 +03:00
|
|
|
console.log(Color[c]); // "Green"
|
2014-08-14 14:12:50 +04:00
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Lastly, "void" is used in the special case of a function returning nothing
|
2014-08-14 14:12:50 +04:00
|
|
|
function bigHorribleAlert(): void {
|
|
|
|
alert("I'm a little annoying box!");
|
|
|
|
}
|
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Functions are first class citizens, support the lambda "fat arrow" syntax and
|
|
|
|
// use type inference
|
|
|
|
|
2017-08-23 11:14:39 +03:00
|
|
|
// The following are equivalent, the same signature will be inferred by the
|
2015-03-10 23:09:35 +03:00
|
|
|
// compiler, and same JavaScript will be emitted
|
2017-05-25 18:35:08 +03:00
|
|
|
let f1 = function (i: number): number { return i * i; }
|
2015-03-10 23:09:35 +03:00
|
|
|
// Return type inferred
|
2017-05-25 18:35:08 +03:00
|
|
|
let f2 = function (i: number) { return i * i; }
|
2016-11-20 23:41:16 +03:00
|
|
|
// "Fat arrow" syntax
|
2017-05-25 18:35:08 +03:00
|
|
|
let f3 = (i: number): number => { return i * i; }
|
2016-11-20 23:41:16 +03:00
|
|
|
// "Fat arrow" syntax with return type inferred
|
2017-05-25 18:35:08 +03:00
|
|
|
let f4 = (i: number) => { return i * i; }
|
2016-11-20 23:41:16 +03:00
|
|
|
// "Fat arrow" syntax with return type inferred, braceless means no return
|
|
|
|
// keyword needed
|
2017-05-25 18:35:08 +03:00
|
|
|
let f5 = (i: number) => i * i;
|
2014-08-14 17:40:21 +04:00
|
|
|
|
2024-05-15 05:34:54 +03:00
|
|
|
// Functions can accept more than one type
|
|
|
|
function f6(i: string | number): void {
|
|
|
|
console.log("The value was " + i);
|
|
|
|
}
|
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Interfaces are structural, anything that has the properties is compliant with
|
|
|
|
// the interface
|
2014-08-14 14:12:50 +04:00
|
|
|
interface Person {
|
|
|
|
name: string;
|
2015-03-10 23:09:35 +03:00
|
|
|
// Optional properties, marked with a "?"
|
2014-08-14 17:40:21 +04:00
|
|
|
age?: number;
|
2015-03-10 23:09:35 +03:00
|
|
|
// And of course functions
|
2014-08-27 17:41:12 +04:00
|
|
|
move(): void;
|
2014-08-14 17:40:21 +04:00
|
|
|
}
|
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Object that implements the "Person" interface
|
|
|
|
// Can be treated as a Person since it has the name and move properties
|
2017-05-25 18:35:08 +03:00
|
|
|
let p: Person = { name: "Bobby", move: () => { } };
|
2015-03-10 23:09:35 +03:00
|
|
|
// Objects that have the optional property:
|
2017-05-25 18:35:08 +03:00
|
|
|
let validPerson: Person = { name: "Bobby", age: 42, move: () => { } };
|
2015-03-10 23:09:35 +03:00
|
|
|
// Is not a person because age is not a number
|
2017-05-25 18:35:08 +03:00
|
|
|
let invalidPerson: Person = { name: "Bobby", age: true };
|
2014-08-14 14:12:50 +04:00
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Interfaces can also describe a function type
|
2014-08-14 14:12:50 +04:00
|
|
|
interface SearchFunc {
|
|
|
|
(source: string, subString: string): boolean;
|
|
|
|
}
|
2015-03-10 23:09:35 +03:00
|
|
|
// Only the parameters' types are important, names are not important.
|
2017-05-25 18:35:08 +03:00
|
|
|
let mySearch: SearchFunc;
|
|
|
|
mySearch = function (src: string, sub: string) {
|
2014-08-14 17:40:21 +04:00
|
|
|
return src.search(sub) != -1;
|
2014-08-14 14:12:50 +04:00
|
|
|
}
|
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Classes - members are public by default
|
2014-08-14 17:40:21 +04:00
|
|
|
class Point {
|
2015-03-10 23:09:35 +03:00
|
|
|
// Properties
|
2015-11-28 02:30:23 +03:00
|
|
|
x: number;
|
2015-03-11 00:58:18 +03:00
|
|
|
|
2015-11-28 02:30:23 +03:00
|
|
|
// Constructor - the public/private keywords in this context will generate
|
|
|
|
// the boiler plate code for the property and the initialization in the
|
|
|
|
// constructor.
|
|
|
|
// In this example, "y" will be defined just like "x" is, but with less code
|
|
|
|
// Default values are also supported
|
2015-03-10 23:09:35 +03:00
|
|
|
|
2015-11-28 02:30:23 +03:00
|
|
|
constructor(x: number, public y: number = 0) {
|
|
|
|
this.x = x;
|
|
|
|
}
|
2015-03-11 00:58:18 +03:00
|
|
|
|
2015-11-28 02:30:23 +03:00
|
|
|
// Functions
|
2020-03-21 20:20:23 +03:00
|
|
|
dist(): number { return Math.sqrt(this.x * this.x + this.y * this.y); }
|
2015-03-11 00:58:18 +03:00
|
|
|
|
2015-11-28 02:30:23 +03:00
|
|
|
// Static members
|
|
|
|
static origin = new Point(0, 0);
|
2014-08-14 17:40:21 +04:00
|
|
|
}
|
2014-08-14 14:12:50 +04:00
|
|
|
|
2018-10-19 15:55:51 +03:00
|
|
|
// Classes can be explicitly marked as implementing an interface.
|
2018-10-30 20:40:01 +03:00
|
|
|
// Any missing properties will then cause an error at compile-time.
|
2018-10-19 15:55:51 +03:00
|
|
|
class PointPerson implements Person {
|
|
|
|
name: string
|
|
|
|
move() {}
|
|
|
|
}
|
|
|
|
|
2017-05-25 18:35:08 +03:00
|
|
|
let p1 = new Point(10, 20);
|
|
|
|
let p2 = new Point(25); //y will be 0
|
2014-08-14 17:56:30 +04:00
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Inheritance
|
2014-08-14 17:56:30 +04:00
|
|
|
class Point3D extends Point {
|
2015-11-28 02:30:23 +03:00
|
|
|
constructor(x: number, y: number, public z: number = 0) {
|
|
|
|
super(x, y); // Explicit call to the super class constructor is mandatory
|
|
|
|
}
|
2015-03-11 00:58:18 +03:00
|
|
|
|
2015-11-28 02:30:23 +03:00
|
|
|
// Overwrite
|
2020-03-21 20:20:23 +03:00
|
|
|
dist(): number {
|
2017-05-25 18:35:08 +03:00
|
|
|
let d = super.dist();
|
2020-03-21 20:20:23 +03:00
|
|
|
return Math.sqrt(d * d + this.z * this.z);
|
2015-11-28 02:30:23 +03:00
|
|
|
}
|
2014-08-14 17:56:30 +04:00
|
|
|
}
|
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Modules, "." can be used as separator for sub modules
|
2014-08-27 17:41:12 +04:00
|
|
|
module Geometry {
|
|
|
|
export class Square {
|
|
|
|
constructor(public sideLength: number = 0) {
|
|
|
|
}
|
|
|
|
area() {
|
|
|
|
return Math.pow(this.sideLength, 2);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-25 18:35:08 +03:00
|
|
|
let s1 = new Geometry.Square(5);
|
2014-08-27 17:41:12 +04:00
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Local alias for referencing a module
|
2014-08-27 17:41:12 +04:00
|
|
|
import G = Geometry;
|
|
|
|
|
2017-05-25 18:35:08 +03:00
|
|
|
let s2 = new G.Square(10);
|
2014-08-14 14:12:50 +04:00
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Generics
|
|
|
|
// Classes
|
2014-08-31 19:57:44 +04:00
|
|
|
class Tuple<T1, T2> {
|
2015-11-28 02:30:23 +03:00
|
|
|
constructor(public item1: T1, public item2: T2) {
|
|
|
|
}
|
2014-08-31 19:57:44 +04:00
|
|
|
}
|
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Interfaces
|
2014-08-31 19:57:44 +04:00
|
|
|
interface Pair<T> {
|
2015-11-28 02:30:23 +03:00
|
|
|
item1: T;
|
|
|
|
item2: T;
|
2014-08-31 19:57:44 +04:00
|
|
|
}
|
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// And functions
|
2017-05-25 18:35:08 +03:00
|
|
|
let pairToTuple = function <T>(p: Pair<T>) {
|
2015-11-28 02:30:23 +03:00
|
|
|
return new Tuple(p.item1, p.item2);
|
2014-08-31 19:57:44 +04:00
|
|
|
};
|
|
|
|
|
2017-05-25 18:35:08 +03:00
|
|
|
let tuple = pairToTuple({ item1: "hello", item2: "world" });
|
2014-08-14 15:34:41 +04:00
|
|
|
|
2015-03-10 23:09:35 +03:00
|
|
|
// Including references to a definition file:
|
2014-08-14 17:40:21 +04:00
|
|
|
/// <reference path="jquery.d.ts" />
|
|
|
|
|
2015-10-19 16:09:58 +03:00
|
|
|
// Template Strings (strings that use backticks)
|
2015-10-19 18:40:57 +03:00
|
|
|
// String Interpolation with Template Strings
|
2017-05-25 18:35:08 +03:00
|
|
|
let name = 'Tyrone';
|
|
|
|
let greeting = `Hi ${name}, how are you?`
|
2015-10-19 06:38:56 +03:00
|
|
|
// Multiline Strings with Template Strings
|
2017-05-25 18:35:08 +03:00
|
|
|
let multiline = `This is an example
|
2015-10-19 06:38:56 +03:00
|
|
|
of a multiline string`;
|
2015-10-19 06:32:14 +03:00
|
|
|
|
2018-10-03 23:23:54 +03:00
|
|
|
// READONLY: New Feature in TypeScript 3.1
|
|
|
|
interface Person {
|
|
|
|
readonly name: string;
|
|
|
|
readonly age: number;
|
|
|
|
}
|
|
|
|
|
|
|
|
var p1: Person = { name: "Tyrone", age: 42 };
|
2019-10-22 15:16:52 +03:00
|
|
|
p1.age = 25; // Error, p1.age is read-only
|
2018-10-03 23:23:54 +03:00
|
|
|
|
|
|
|
var p2 = { name: "John", age: 60 };
|
|
|
|
var p3: Person = p2; // Ok, read-only alias for p2
|
2019-01-27 18:06:34 +03:00
|
|
|
p3.age = 35; // Error, p3.age is read-only
|
|
|
|
p2.age = 45; // Ok, but also changes p3.age because of aliasing
|
2018-10-03 23:23:54 +03:00
|
|
|
|
|
|
|
class Car {
|
|
|
|
readonly make: string;
|
|
|
|
readonly model: string;
|
|
|
|
readonly year = 2018;
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
this.make = "Unknown Make"; // Assignment permitted in constructor
|
|
|
|
this.model = "Unknown Model"; // Assignment permitted in constructor
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let numbers: Array<number> = [0, 1, 2, 3, 4];
|
|
|
|
let moreNumbers: ReadonlyArray<number> = numbers;
|
|
|
|
moreNumbers[5] = 5; // Error, elements are read-only
|
|
|
|
moreNumbers.push(5); // Error, no push method (because it mutates array)
|
|
|
|
moreNumbers.length = 3; // Error, length is read-only
|
|
|
|
numbers = moreNumbers; // Error, mutating methods are missing
|
2019-06-17 12:22:58 +03:00
|
|
|
|
2019-07-04 00:15:10 +03:00
|
|
|
// Tagged Union Types for modelling state that can be in one of many shapes
|
2024-04-19 07:34:40 +03:00
|
|
|
type State =
|
2019-07-04 00:15:10 +03:00
|
|
|
| { type: "loading" }
|
|
|
|
| { type: "success", value: number }
|
|
|
|
| { type: "error", message: string };
|
|
|
|
|
|
|
|
declare const state: State;
|
|
|
|
if (state.type === "success") {
|
|
|
|
console.log(state.value);
|
|
|
|
} else if (state.type === "error") {
|
|
|
|
console.error(state.message);
|
|
|
|
}
|
|
|
|
|
2021-11-10 02:08:47 +03:00
|
|
|
// Template Literal Types
|
|
|
|
// Use to create complex string types
|
|
|
|
type OrderSize = "regular" | "large";
|
|
|
|
type OrderItem = "Espresso" | "Cappuccino";
|
|
|
|
type Order = `A ${OrderSize} ${OrderItem}`;
|
|
|
|
|
|
|
|
let order1: Order = "A regular Cappuccino";
|
|
|
|
let order2: Order = "A large Espresso";
|
|
|
|
let order3: Order = "A small Espresso"; // Error
|
|
|
|
|
2019-06-17 12:22:58 +03:00
|
|
|
// Iterators and Generators
|
|
|
|
|
|
|
|
// for..of statement
|
|
|
|
// iterate over the list of values on the object being iterated
|
2019-06-17 12:26:28 +03:00
|
|
|
let arrayOfAnyType = [1, "string", false];
|
2019-06-18 09:51:00 +03:00
|
|
|
for (const val of arrayOfAnyType) {
|
2019-06-17 12:26:28 +03:00
|
|
|
console.log(val); // 1, "string", false
|
|
|
|
}
|
|
|
|
|
2019-06-17 12:22:58 +03:00
|
|
|
let list = [4, 5, 6];
|
2019-06-18 09:51:00 +03:00
|
|
|
for (const i of list) {
|
2019-07-31 10:36:54 +03:00
|
|
|
console.log(i); // 4, 5, 6
|
2019-06-17 12:22:58 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// for..in statement
|
|
|
|
// iterate over the list of keys on the object being iterated
|
2019-06-18 09:51:00 +03:00
|
|
|
for (const i in list) {
|
2019-07-31 10:36:54 +03:00
|
|
|
console.log(i); // 0, 1, 2
|
2019-06-17 12:22:58 +03:00
|
|
|
}
|
|
|
|
|
2019-10-11 22:53:07 +03:00
|
|
|
// Type Assertion
|
2019-06-17 12:22:58 +03:00
|
|
|
|
2019-10-11 22:53:07 +03:00
|
|
|
let foo = {} // Creating foo as an empty object
|
|
|
|
foo.bar = 123 // Error: property 'bar' does not exist on `{}`
|
|
|
|
foo.baz = 'hello world' // Error: property 'baz' does not exist on `{}`
|
2019-06-17 12:22:58 +03:00
|
|
|
|
2024-04-19 07:34:40 +03:00
|
|
|
// Because the inferred type of foo is `{}` (an object with 0 properties), you
|
2019-10-11 22:53:07 +03:00
|
|
|
// are not allowed to add bar and baz to it. However with type assertion,
|
|
|
|
// the following will pass:
|
|
|
|
|
2024-04-19 07:34:40 +03:00
|
|
|
interface Foo {
|
2019-10-11 22:53:07 +03:00
|
|
|
bar: number;
|
|
|
|
baz: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
let foo = {} as Foo; // Type assertion here
|
|
|
|
foo.bar = 123;
|
|
|
|
foo.baz = 'hello world'
|
2014-08-14 17:40:21 +04:00
|
|
|
```
|
2014-08-14 14:12:50 +04:00
|
|
|
|
|
|
|
## Further Reading
|
2024-04-19 07:34:40 +03:00
|
|
|
|
|
|
|
* [Official TypeScript website](https://www.typescriptlang.org/)
|
|
|
|
* [Source code on GitHub](https://github.com/microsoft/TypeScript)
|
|
|
|
* [Learn TypeScript](https://learntypescript.dev/)
|