This cheat sheet is not exhaustive. It covers the TypeScript syntax subset used in this book. For a full TypeScript reference, see http://www.typescriptlang.org/docs.
Type |
Description |
---|---|
boolean | Can be true or false. |
number | 64-bit floating-point number. |
string | UTF-16 Unicode string. |
void | Type used as return type for functions that don’t return meaningful values. |
undefined | Can be only undefined. Represents, for example, a variable that was declared but not initialized. |
null | Can be only null. |
object | Represents an object or nonprimitive type. |
unknown | Can represent any value. Type-safe, so it isn’t implicitly converted to another type. |
Any | Bypasses type checking. Type-unsafe and automatically converted to any other type. |
Never | Cannot represent any value |
Description |
|
---|---|
string[] | Array types are denoted by [] after the type name—in this case, an array of strings. |
[number, string] | Tuples are declared as a list of types within []—in this case, a number and a string, such as [0, "hello"]. |
(x: number, y: number) => number; | Function types are declared as a list of arguments in (), then =>, then the return type. |
enum Direction { North, East, South, West, } |
Enumerations are declared with the keyword enum. In this case, a value can be one of the literals North, East, South, or West. |
type Point { X: number, Y: number } |
A type with X and Y properties of type number. |
interface IExpression { evaluate(): number; } |
An interface with an evaluate() method that returns a number. |
class Circle extends Shape implements IGeometry { // ... } |
Circle class extending the Shape base class and implementing the IGeometry interface. |
type Shape = Circle | Square; | Union types are declared as an |-separated list of types. Shape is either a Circle or a Square. |
type SerializableExpression = Serializable & Expression; |
Intersection types are declared as a &-separated list of types. SerializableExpression has both all members of Serializable and all members of Expression. |
Example |
Description |
---|---|
let x: unknown = 0; let y: number = <number>x; type Point = { x: number; y: number; } function isPoint(p: unknown): p is Point { return ((<Point>p).x !== undefined) && ((<Point>p).y !== undefined); } let p: unknown = { x: 10, y: 10 }; if (isPoint(p)) { // p is of type Point here p.x -= 10; } |
Specifying a type between <> before a value reinterprets the value as that type. x can be assigned to y only after being explicitly reinterpreted as number. A type predicate is a boolean that states that a variable is of a certain type. If we reinterpret p as a Point, and it has both an x and a y member (neither is undefined), p is a Point. Within an if statement where a type predicate is true, the tested value is automatically reinterpreted as having that type. |
3.144.96.159