Types | |
---|---|
Primitives | |
Boolean | True or false |
Number | Decimal, hex, binary, or ocatal |
String | "string" or 'string' or `string` |
Null | Absense of a value |
Undefined | myVar name; // Undefined |
bigint | Very large integers |
symbol | Creates a globally unique referenceSymbol("s") !== Symbol("s"); |
Others | |
Array | type[] = [val1, val2, …] , orArray<type> = [val1, val2, …] |
Tuple | let x: [type1, type2, …] |
Enum | enum Numbers {One = 1, …}
Numbers.One === 1; // true , orenum Strings {One = "one", …} |
Any | Opt-out of type checking; value passes compile-time checkslet unknown: any; |
Void | Opposite of any: absence of any typefunction nothing(): void {} |
Never | Represents type of values that never occur |
Object | Non-primitive type |
Concepts | |
---|---|
Primitive types | String, number, boolean, etc. |
Type inference | let name = 'Fluffy'; |
Shape of an object | TypeScript knows and enforces the properties of objects. |
Type annotations | let myVariable: type; |
Type assertions | x!.toString(); // Stating that x is the right type |
strictNullChecks | Enforces using null and undefined explicitly. |
Namespaces | Organise code by wrapping variables, classes, etc. together. |
Narrowing | Validation that ensures variables are a particular type. |
Declarations | |
---|---|
Variables | let isDone: boolean = false; |
Literals | const pi = 3.14; // π |
Untion types | let age: string | number; |
Type guards | |
---|---|
Primitive | if (typeof padding === "number") {} |
User-defined | isFish(pet: Fish | Bird): pet is Fish => { |
Functions | |
---|---|
Argument type | function myFn (arg: type) {} |
Return type | function myFn (arg): type {} |
Arrow form | myFn (arg: type): type => {} |
Interfaces | |
---|---|
Explicit | interface Options { |
Inline | myFn (opts: {x: number}) => {} |
Optional properties | interface Options { |
Readonly properties | interface Options { |
Mapped types | type Dynamic { |
Generics | |
---|---|
Basic declaration | function id<Type>(arg: Type): Type {return arg;} |
Calling it explicity | id<string>("hi"); |
Calling it, inferred | id("hi"); // returns "hi" |
Unique name | function id<primitive>(arg: primitive):
primitive {return arg;} |
Interface | interface GenericIdentityFns {
<Type>(arg: Type): Type;} |
Generic constraints | interface Numeric { |
Type parameters in generic constraints | function<Type, Key extends keyof Type>(…) {} |
Namespaces | |
---|---|
Basic example | namespace helpers { |
Multi-file namespaces | /// <reference path="Validation.ts" /> |
Aliases | import Triangles = Shapes.Polygons.Triangles; |
Operators | |
---|---|
keyof type operator | type Point = {x: number}; |
typeof type operator | let greet = "hello"; |