Syntax
Contrary to other typed languages, TypeScript doesn’t use “types on the left”-style declarations like int x = 0;
. In TypeScript, type annotations go after the value being typed.
const x: number = getSomeNum()
let y: string[] = [] // array of strings
function fn(x: number, y?: string): boolean { ... }
let fn: (x: number, y?: string) => boolean = (x, y) => ...;
type Sample = {
x: number;
y: string[];
z?: boolean; // Optional
// functions
fn: (x: number) => void; // Arrow func field
fn(x: number): void; // Function
// Callable types
(): void; // Type can be executed
(x: number): number; // Overloaded type
new (s: string): Sample; // Newable e.g. new Sample('foo')
[key: string]: number; // Accepts any key value pairs
readonly prop: string; // Readonly property
}
There are also interface
s. And class
es can be used as types.
🚨 HINT: Use the TS cheat sheets: https://www.typescriptlang.org/cheatsheets
Structural Types
Objects and values are not of a single type because TypeScript's type system is structural, not nominal. So, the relationships between types are determined by the properties inside and not by a particular type:
class Phone {
on() {}
off() {}
}
class TV {
on() {}
off() {}
changeChannel() {}
}
// Note that the extra property in TV doesn’t
// prevent assignment since it has all the
// required properties in Phone.
let Samsung: Phone = new TV()
Type-erased output
TypeScript's type system is fully erased, meaning that the output code will be "type-erased" and won't contain any reference to the TS types. So, if we wanted to use reflection to determine the type of a value, it won't know about TypeScript types:
typeof (new Phone()) // "object", not "Phone"
Primitive Types
TypeScript has primitive types for all the JavaScript built-in types:
number
string
bigint
boolean
symbol
null
undefined
object
The type names String, Number, and Boolean (starting with capital letters) are legal, but refer to some special built-in types that will very rarely appear in your code. Always use string, number, or boolean for types.
Other important TypeScript types
Type | Explanation |
---|---|
any | turns off the type checker wherever it appears |
object literal | eg { property: Type }
|
void | a subtype of undefined intended for use as a return type, eg (): void;
|
T[] | arrays, eg number[] , string[] , also written Array<T>
|
[T, T] | tuples, which are fixed length but mutable, eg [number, number, string]
|
(t: T) => U | functions, eg (count: number) => void;
|
"explicit" | unit types, eg (val: "foo" │ "bar"): void;
|
Unions ("OR") / Intersections ("AND")
With unions, we can tell TypeScript a type can have two or more different shapes, while intersections tell TypeScript to see it as a single type.
type A = { foo: string };
type B = { bar: number };
type C = A | B; // either or, but not both
type D = A & B & { baz: () => void }; // { foo, bar, baz }
Note: there can be conflicts:
type Conflict = { a: number } & { a: string };
Top comments (0)