TypeScript is a super-set of JavaScript that enforce the code quality. This cheat sheet summarizes all the syntax and features of the language.
Usage
npm install typescript
> tsc hello-world.ts
Primitives types
Any type (explicitly untyped)
let whatever: any = "anything";
Void type (null or undefined, use for function returns only)
function nothing(): void {}
String
let myString: string = "hello";
Number
let myNumber: number = 1;
Boolean
let mybool: boolean = true;
Arrays
Array of strings
string[] or Array<string>
Array of functions that return boolean
{(): boolean;}[] or Array<()=>boolean>
current version: 3.7 - Date: Oct 2021
Named types
Enum
enum Size {
S = 'small',
L = 'large',
XL = 'xlarge'
};
Interface
interface IPerson {
firstname: string;
age?: number; //optional
sayHello(): void;
size?: Size;
}
Class
class Person implement IPerson {
firstname: string;
age: number;
size: Size = Size.L;
constructor() {}
sayHello(): void {};
}
Object type literals
Object with implicit properties
{ foo: 'hello'; bar: 5 } or { foo; 'hello'; }
Object with optional property
{ required: boolean; optional?: number; }
Hash map
{ [key: string]: Type; }
Indexable types
{ [id: number]: Type; }