TypeScript
Overloads
Cheat Sheet
Common Syntax Optionally take properties from
existing interface or type
A callable interface can have multiple definitions
for different sets of parameters
Interface interface JSONResponse extends Response, HTTPAble {
version: number;
interface Expect {
JSDoc comment attached to show in editors
h
(matc er: boolean): strin g
Key points (matcher: string): boolean;
/** In bytes */
}
Used to describe the shape of payloadSize: number;
This property might not be on the object
objects, and can be extended by
others.
Get & Set
outOfStock?: boolean;
These are two ways to describe a
property which is a function
Almost everything in JavaScript is
an object and interface is built update: (retryTimes: number) => void;
Objects can have custom getters or setters
to match their runtime behavior. update(retryTimes: number): void;
interface Ruler {
You can call this object via () - ( functions get size(): numbe r
(): JSONResponse
in JS are objects which can be called )
set size(value: number | string);
Built-in Type Primitives }
new(s: string): JSONResponse;
You can use new on the object
this interface describes
boolean, string, number,
undefined, null, any, Usage
[key: string]: number;
unknown, never, void, Any property not described already is assumed
bigint, symbol to exist, and all properties must be numbers const r: Ruler = ...
readonly body: string;
.
r size = 12
Common Built-in JS Objects } r.size = "36"
Tells TypeScript that a property
can not be changed
Date, Error, Array, Map,
Set, Regexp, Promise
Type Literals Extension via merging
Object:
Generics Type parameter
Interfaces are merged, so multiple declarations will
{ field: string }
add ne w fields to the type definition.
Declare a type which can change in your interface
Function:
interface API all {
C
(arg: number) => string
C
interface API all<Response> {
data: Response
Arrays:
data: Response
string[] or Array<string>
}
Tuple:
U sed here
C
interface API all {
[string, number] Usage
error?: Error
C
const api: API all<Artwork all> = C ...
}
Avoid
api data . // Artwork
Sets a constraint on the type
Object, String, Number, Boolean which means only types with a
You can constrain what types are accepted into the generic ‘ ’
status property can be used
Class conformance
parameter via the extends keyword.
C
interface API all<Response extends { status: number }> {
You can ensure a class conforms to an interface via implements:
data: Response
interface Syncable { sync(): void }
}
class Account implements Syncable { ... }
C
const api: API all<Artwork all> = C ...
.
api data status.