Basic Types
Boolean
Number
String
Array
Tuple
Tuple types allow you to epxress an array with a fixed number of elements whose types are known, but need not be the same.
Enum
An enum is a way of giving more friendly names to sets of numeric values. By default, enums begin numbering starting at 0.
Unknown
Values with unknown
type may come from dynamic content (from user) or we may want to intentionally accept all values in our API.
We could narrow the value with unknown
type down with typeof
checks, comparison checks, or other advanced type guards.
Any
In some situations, not all type information is available or its declaration would take an inappropriate amount of effort. In these cases, we might want to opt-out of type checking. To do so, we label these values with the any
type:
Type safety is one of the main motivations for using TypeScript and you should try to avoid using any when not necessary.
Void
void
means the absence of having any type at all. You may commonly see this as the return type of functions that do not return a value:
Null and Undefined
In TypeScript, both undefined
and null
actually have their types named undefined
and null
respectively.
By default null
and undefined
are subtypes of all other types. That means you can assign null
and undefined
to something like number
.
However, when using the --strictNullChecks
flag, null
and undefined
are only assignable to unknown
, any
and their respective types (the one exception being that undefined
is also assignable to void
).
Never
The never
type represents the type of values that never occur. The never
type is a subtype of, and assignable to, every type. However, no type is assignable to never
.
Object
object
is a type that represents the non-primitive type. With object
type, APIs like Object.create
can be better represented.
Type assertions
Type assertions are a way to tell the compiler "trust me, I know what Iām doing."
as
syntax
"angle-bracket" syntax
Last updated