Typescript Basics
Introduction and cheatsheet for basic Typescript concepts
Updated: 03 September 2023
Types
A type
is the most basic thing in typescript and is an object structure
We can also create option types which specify what the allowed values are for a type
Below is an option type
Here’s a type that uses the option type
Types can be composed
Merging types
Optional types
Interfaces
Next, we have interfaces, it’s like a type, but can’t be composed like the above types
Note that an interface doesn’t use
=
like atype
Interfaces can be extended
Interface extension is similar to type merging, but with a bit of a different syntax
Type helpers
Typescript provides us with some base types that we can use to achieve interesting compositions
Arrays
Array types, can use Array
or []
(both are the same)
MyArray1 and MyArray2 are the same
Partial
Partial
makes all top-level properties of a type optional
The equivalent of the above with interfaces, where we extend a partial type to add an id
property
Required
We can also have the Required
type, where all top-level props are required
Records
Another useful one is the Record
type. which lets us specify an object’s key and value type. Usually one or both of these are an option type
We can also have both values be option types
Generics
In the above examples, the helper types are using generics. Below is a generic that allows us to specify a user with type of an id
And similarly, an interface based implementation
Although we can use T
for the generic, (or any other letter), we usually give it something more meaningful. e.g. Key/Value pairs, use K
and V, or a type of Data may be
TData`
We can also use generics with multiple parameters like so:
Values
Values are (an object or function which matches the type). We can use the above defs in order to define a value
Also note that you cannot log or use a type as data, e.g. the following will be an error
This is because types don’t exist at runtime. they’re just a developer tool
Functions
Types can also be used to defined functions (interfaces can’t do this)
We can also use generics for function definitions like so
In the below function, we say that the entire function is of type GetPerson
In the below function, ID
is the type of the params, Promise<Person>
is the return type
Classes
In general, we can also implement class properties like so
However, it’s often desirable to create an interface that a class should amtch, for example
TID
below has a defualt value of ID
A class can use that interface like so
Examples
Below is a link to the runnable Repl.it that has the above code defined