TypeScript Cheat Sheet
TypeScript Cheat Sheet
Class
A TypeScript class has a few type-specific extensions to ES2015 JavaScript These features are TypeScript specific language extensions which may
Key points
Cheat Sheet classes, and one or two runtime additions. never make it to JavaScript with the current syntax.
id: string;
// A field
class Location {
name!: string;
// A ‘trust me, it’s there’ field
}
private x vs #private
#attributes: Map<any, any>;
// A private field
const loc = new Location(20, 40);
inside the JavaScript engine that it set ame(name: string) { t [Link] = name }
is only accessible inside the class: verifyName = (name: string) = > { ... }
function fields)
"
[Link]( Hello , " + h
t [Link] ame())N ;
overload definitions }
sync(cb: ((result: string) => void)): void
‘this’ in classes
The value of ‘this’ inside a function sync(cb?: ((result: string) => void)): void | Promise<{ ... }> { ... }
parameters to methods.
the bind function, or arrow ... checking, public is the default.
functions to work around the issue import {
when it occurs.
u u 0;
Syncable, triggersSync, f
pre erCac e h , re quired
static # serCo nt =
Static fields / methods
static registerUser(user: User) { ... }
} from "mylib"
}
const a:Bag = new Bag()
@triggers Sync()
Generics class Bo
contents: Type
So, be careful to not do this: Declare a type which can constructor(value: Type) {
@pre ferCache(false)
methods.
}
Used here
}
update(@required f
in o: Partial<User>) { ... }
Cheat Sheet
If Statements Expressions
Control
const input = getUserInput()
typeof (for primitives) “property” in object (for objects) input // string | number
Flow
const input = getUserInput()
const inputLengt h =
:
Analysis
// input string
if (typeof input === “string”) {
if (“error” in input) {
input // string
input // { error : ... }
} }
} }
Most of the time CFA works
inside natural JavaScript
boolean logic, but there are
ways to define your own Discriminated Unions Usage Assignment
functions which affect how
TypeScript narrows types. type Responses =
R
const response = get esponse()
Narrowing types using ‘as const’
| { status: 200, data: any }
response // Responses
‘widened’ -
to a non literal version. The prefix ‘as
case 200: return response. at d a
const’ locks all types to their literal versions.
case 301: d
return re irect([Link])
} }
} E R
if (is rror esponse(response)) {
Assertion Functions scope, because it throws instead of returning false. [Link] // SuccessResponse
R
const res = get esponse() :
SuccessResponse ErrorResponse
! j instanceof SuccessResponse))
if ( (ob {
data: ..
throw new Error(“Not a success!”)
R
assert esponse(res )
data r
= "Hello"
}
data // string
TypeScript
Overloads
Cheat Sheet
Common Syntax Optionally take properties from
version: number;
interface Expect {
/** In bytes */
}
Used to describe the shape of payloadSize: number;
interface Ruler {
You can call this object via () - ( functions get size(): numbe r
(): JSONResponse
bigint, symbol to exist, and all properties must be numbers const r: Ruler = ...
Arrays:
data: Response
string[] or Array<string>
}
Tuple:
U sed here
C
interface API all {
C
const api: API all<Artwork all> = C ...
}
Avoid
api data . // Artwork
Sets a constraint on the type
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
}
class Account implements Syncable { ... }
C
const api: API all<Artwork all> = C ...
.
api data status.
TypeScript
Cheat Sheet Type Key points Full name is “type alias” and are used
to provide names to type literals
Supports more rich type-system
features than interfaces.
These features are great for building libraries, describing existing
JavaScript code and you may find you rarely reach for them in
mostly TypeScript applications.
^ s
interface comparison checks /** In bytes */
// Attached docs
Loop through each field
Sets type as a function with
can be faster. payloadSize: number;
//
in the type generic type Subscriber<Type> = {
original type as param
outOfStock?: boolean;
// Optional
parameter “Type”
[Property in keyof Type]:
similar semantics.
new (s: string): JSONResponse;
// Newable
// bio: (nv: string) => void }
Build with Utility Types readonly body: string;
// Readonly property
Useful for documentation mainly Describes a type which is one of many options, Re-use the type from an existing JavaScript : never
for example a list of known strings. runtime value via thetypeof operator.
type SanitizedInput = string;
type Size =
const data = { ... }
type Animals = Bird | Dog | Ant | Wolf;
x: number;
A way to merge/extend types Re-use the return value from a
Template Union Types
y: number;
type Location =
// { x: number, y: number }
Tuple Type ReturnType<typeof createFixtures>
type AllLocaleIDs =
type Data = [
a subset of a type. Type from Module `${SupportedLangs}_${FooterLocaleIDs}_id`;
// "en_header_id" | "en_footer_id"
location: Location,
type Response = { data: { ... } }
| "pt_header_id" | "pt_footer_id"
// { ... }