TS is a structurally-typed language: so long as 2 types have the same structure, they are equal (AKA “duck typing”)
readonly
and as const
by defaultsatisfies
by default instead of : Type
string
togethernull
or undefined
interface
until you run into an issue which type
would solve (types require using intersections, interfaces can always use extends
)Union
s are really the intersection between the types that conform it (only attributes and functions available to all elements of the union can be used)type
is merely an alias. It doesn't actually create new types (e.g. type sanitizedInput = string
is still a string)as
to enforce a type (type assertion) when you know it can be done, but careful since they are removed at compile-time. Can only be done from a more specific or less specific type.(… as any)
to then convert to a specific type when the direct type assertion is not possible. HEAVILY DISCOURAGED.Literal
types are one-possible-value types (constants)
Literal
type unions are extremely useful (e.g. alignment: "left" | "center" | "right"
)method: "GET" as "GET"
, since otherwise method
would’ve been inferred as string
, or to set an entire object as const
to set all properties as literals.!!
operator causes the value to be a literal type true
or false
, not a boolean
function isSomeType (arg: SomeUnion): arg is SomeType
is called a type predicate and is used to narrow a type in a custom manner using a function. Classes can also use this is SomeType
for this purpose.Symbol(string)