0% found this document useful (0 votes)
3 views

Typescript cheat sheet

This TypeScript cheat sheet covers various concepts including control flow, type narrowing, type guards, interfaces, classes, generics, and utility types. It provides syntax examples and key points for understanding how to effectively use TypeScript features. The document serves as a quick reference for developers to enhance their TypeScript coding skills.

Uploaded by

yepiwed516
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Typescript cheat sheet

This TypeScript cheat sheet covers various concepts including control flow, type narrowing, type guards, interfaces, classes, generics, and utility types. It provides syntax examples and key points for understanding how to effectively use TypeScript features. The document serves as a quick reference for developers to enhance their TypeScript coding skills.

Uploaded by

yepiwed516
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

TypeScript

Cheat Sheet If Statements Expressions


Most narrowing comes
from
expressions it statements,
inside Narowing also occurs on the same line as code, when
doing boolean operationss

Control where diferent type operators naTow inside the new scope

typeof (for primitives) property in object (for objects)


const input
1nput /
=getUserInput
string number
()
Flow const input
input
getuserInput()
string number
const
1nput /
input
string
getUserInput ()
error: const inputLength
(typeof input "string" && input. length) |I| input

Analysis if (typeof input "string") { if ("error" in input)


1nput ertor.
Iinput. string

Key points instanceof (for classes) type-guard functions (tor anything)

const input = getuserInput ()


CFA nearly always takes funion
a const input=
1nput
getuserInput
nuimber numberl
()
and reduces the number input number numbert

types inside the union based on if (input instanceof Array i if (Array.isArray(input)) {


logic in your code.
Input // numberL J input / numberl

Most of the time CFA works


nsiae natural Javascnpt
DOOlean logic, Dut there are Discriminated Unions
functions which affect how
Usage Assignment
TypeScript narrows types type Responses const response getResponse) Narrowing types using 'as const
status: 200, data: any response / Responses
Subfields in objects are treated as though they can
status: 301, to: string
status:_u00, error: Error ) Switch(response.status) { De mutared, and auring assignment tne ype WII De
case 200: return response.dataa widened to
a non-literal version. The prefix 'as
const locks all types to their literal
All members of the union have the same
case 301: return redirect(response.to) versions
case 4Oe: return response.error {
property name, CA can discriminate on that const
datal
name:
=

"Lagreus
typeof datal =t
name String

ype Guards witha retum type describing the CFA


change fora new scope when it is true. Usage
const dataz
name.Lagreus
t
»
Typeof data2=t
name: "Zagreus"
const response getResponse) a s const

function isErrorResponse(obj: Response): obj is APIErrorResponse response/Response| APIErrorResponse


return obj instanceof APIErrorResponse
if (isErrorResponse (response)) í Tracks through related variables
response / APIErrorResponse
Return type position describes const response getResponse()
what the assefton s const 1ssuccessResponse
r e s instanceof SuccessResponse

Assertion Functions ATucion describing


scope, because it throws changesof affecting
CFAinstead retuming the
current
false. Usage (isSuccessResponse)
res.oata i / successkesponse
const res getResponsel)
is res SuccessResponse ErrorResponse Re-assignment updates types
function assertResponselobj: any): asserts obj SuccessResponse t
ltcodj instanceot successkesponse))
throw new Error"Not a assertResponse(res) Assertion functions change
let data: string number=
success the currernt scope or throw
d a t as t r i n g number

res // SuccessResponse data "HelLo"


data // string
Typescript Overloads
Cheat Sheet Common Syntax Opbonally take propertes from
exsting nterace or type

Acallable interface can have mutiple definitions


Interface interface JsONResponse extends Response, HTTPAble {
version: numberi
for different sets of parameters

interface Expect {
Cmatcher: boolean): string
SDoc comment attached to show in editors
Key points /** In bytes *
Cmatcher: string): boolean;
Used to describe
the shape of payloadSize: number
This property might not be on the otect
and can be extended by
objects,
others.
outOfStock?: boolean; These are two ways to describe a
property wnich is a function Get & Set
Aimost everyhing in Java>cnpt is update: (retryTimes: number) => void;
Obyects can have custom getters or setters
match their runtime behavior. update(retryTimes: number): void;
interface Ruler {

O: JsoNResponse
JSONResponse in
n call ths object via ()- (functions
JS are objects which can be called)
get sizeCO: number
set size(value: number| string);
Built-in Iype Primitives
new(s: string): JONResponse; YOu can use new on tre object
this ntertace descnbes
boolean string, number,
undefined, nutt any Tkey: string]: number;. Usage
Any property not described already is assumed
unknown never, vo1d to exist dnd di pGpE LES oi D E a
b1gint, symbol const r: Ruler
readonly body: string r.s1ze 12
Common Built-in JS Objects r.size "36"
els lypescnpt that a property
can not be
Date, Error, Array, Map, cnaye
Set, Regexp, Promise

ype Literals Extension via merging


ODject Generics ypeparameter
field: string }
Interfacesare merged, so multiple declarations will
add new fields to the type definition
Function: Declare a type which can hange in your interface
interface APICall
(arg: number) => string
interface APICall<Response> t data: Response
Arrays data: Response
stringl] or Arrayestring
Tuple: Used here
Lstring, numberJ Usage
interface APICall
error?: Error
const APICall<ArtworkCall>
api:
Avoid =..
api.data / Artwork Sets a constraint on the type
Object, String, Number Boolean which means only types with a
Status property can be used
You canconstrain what types are accepted into the genenic
parameter i a tne extends keywora.
Class conformance
interface APICall<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 {
const api: APICall<ArtworkCall> =

api.data. status
ypeScript
Cheat Sheet Class Key points dlasses, and one hnastwoa few
ecdass or
type-specific extensions
runtime addibons.
to ES2015 JavaScript These features are Iypescnpt specitic language extensions which may
never make t to Javaacript with the curent syntax.

Creating an class instance Ensures that the class Parameter Properties


class ABC ...}
Common Syntax Subclasses this dlass contormis to set ot
a
interfaces or types A
const abc = new ABC() Typescript specificextension to classes which
automaticaly set an instance field to the input parameter.
class User extends Account implements Updatable, Serializable (
class Location
to the new 1d: string; A t1e Ld
Parameters ABC
come
from the constructor tunction. constructor(public x: number, public y: number) {}
displayName?: boolean; // An optional field
// A "trust me, it's there field
private x vs #private name! String const loc new Location (20, 40);
#attributes: Map<any, anyi A przvate field
The prefix private is a type-only rolesl'user"J A lf2eLo
d with defauta
loc.x // 20
addition, and has no effect
at Loc.y 40
class readonly createdAt = new Date) // A readonLy fie ld with a defaulLt
runtime. Code outside of the
into the item in
the
Can reach
following case constructor(1d: string emalt Stngi
YThe code caled on 'new
class Bagt Super(id); Abstract Classes
private item. any this.emall = emai;
In strict: true this code is checked against
the elds to ensure it 5 set up correctly A dass can be declared as not implementable, but as existing to
be subclassed in the type system. As can members of the class.

Vs #private which is runtime abstract class Animal {


prvate and has enforcement Ways to describe dass abstract getNameC): string;
Inside the
Javascrnpt engine that it setName(name: string) t this.name name
methods (and arrow
is only accessible inside the printName ) (
ciasS verifyName =(name: string)>t...) function fieds)
Bag #1tem; any console.log("Hello, "this.getName());
cl A function wth 2
sync): Promise<{ ... }>
this' in classes
void)): void verload definitions
sync cb: ((result: string)
sync(cb?: C(result: string)
>

=> void)) : void| Promise«{.. » . . }class Dog extends Animal ( getName(): . }}


The value of thisthe
inside afunction
depends on
is
how functiontois
cated. tbe the
notclass
guaranteed
instance which get accountIDO } Getters and setters
always
you may be used to in other set accountID(value: string) i } Decorators and Attributes
languages.
privatemakeRequest() { ... } Pmvate access is Just to tis cass, protected You can use decorators on classes, dass methods, accessors, property and
You can use this parameters, use
allows to subdiasses. OnyUsed tor type pararneterS to methods
protected handleRequest() {... )chedking,publicis the defauit
Ond the issue import
ir
when it occurs.
static #userCount = 6;
/ methods
Syncable, triggerssync, prefercache, required
Type and Value
staticregisterUser(user: User) . . . } Staticfields trommy Lib"
a class
Surprise, can be used as esyncable
Dotn a type or a value. static ( this. #userCount = -1 } sengosac
vars. ts eres to ue stduc deSs class User
const
a:Bag new Bag() etriggersSync ()
e
Value class Box< Type> 1Classtype parameter Save)
Generics contents: 1ype
So, be caretul to not do this:
Declare a type which can constructor(value: Type epreferCache(false)
change in your dlass get displayName () { }
class C implements Bag 1}
metnods. this.contents= value; Used here
update(erequired info: Partial<User>) {
const stringBox new Box(a
=
package"
ypescript These features are great for building libraries, describing existing
Cheat Sheet
Type Key poinS to
type alias and are used
Full name ISnames
provide to typeinterds
Supports more nch type-system
Tedures trhan interfaces.
Javasanpt code and you may Tind you rarey reach tor them in
mosty ypescnpt applications
ype vs Interface

Object Literal Syntax Mapped Types


Interfaces can only descnbe
object snape Acts like amapstatementfor thetype system, allowing
ntertaces can be extended by type JSONResponse an input type to change the structure of the new type.
version: number; // Field type Artist = ( name: string, bio: string

interface Comparison checks /** In bytes */ I Attached docs


Loop through each field Sets type as a function with
can be faster in the type generic
payloadSize: number; type SubscriberIype t
pararmeter Type oniginal type as param
outofstock?: bootean IOptional [Property in
keyof Type
Think of Types Like Variables update: (retryTimes: number) => void; // Arrow func field
(newValue: Type[Property]) v o i d
updatelretryl1mes: number ): void; 11 Function
Much likewith you can create
howthe namein / Type is callable
varnables same
( : JsONResponse type ArtistSub = Subscriber<Artist
different scopes, a type has Lkey: stringJ: number ; I/ Accepts any 1ndex t name: (nv: string) vold,
similar semantics.
new (s: string): SONResponse; 11 Newable b i o : (nv: string)void
Build with Utility Types readonly body: stringi // Readonly property

Typescript incudes a lot of Conditional Types


global types which will help you Terser for saving space, see Interface Cheat Sheet for
do common tasks in the type
system. Check the site for them.
more info, everything but 'static matches. Acts as if statements inside
the type system. Created
Va genencS, and then commonly Used to reduce the
number of options in a type union.

Primitive Type Union Type Type from Value type HasFourLegs<Animal> =

Animal extends ( Legs: 4}? Animal


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 sthngs. untme value via the typeot operator.
type SanitizedInput = stringi

type MissingNo = u04; type Size


const data = {... type Animals = Bird| Dog| Ant | Wolf;
"small" | "medium"| "large" type Data = typeof data type FourLegs = HasFourLegs<Animals>

Dog Wolf
Object Literal Type
type Location {
Intersection Types Type from Func Return
Template Union Types
way to merge/extend types Re-use the retum value from a
X number function as a
type
y numDer, type Location: A template string can be used to combine and
const createFixtures = () . . manipulate text inside the type system.
x : number }& t y: number}
type Fixtures "en"I "pt" | "zh";
I / t x : number, y: number}
ReturnType<typeof createFixtures>
type SupportedLangs
type FooterLocaleIDs = "header" "footer"
Tuple Type
Type Indexing funct ion test(fixture: Fixtures) {} type ALlLocaleIDs =
Atuple is aspecial-cased array with known
Ypes at specme indexes. A way to extract and name from S(SupportedLangs}-${FooterLocaleIDs)_id'
type Data l a subset of à ype Type from Module I"en_header id""enfooter_id"
Location: Location type Response data: { . . } const data:
import(". /data"). data
"pt header_id" "pt_footer_id"
timestamp: strin9 "zh_header_ id" "zh_footer_id"
type Data = Response["data"]
..

You might also like