- TS is a structurally-typed language: so long as 2 types have the same structure, they are equal
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)
- Use
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 to a more specific or less specific type.
- Use
(… as any)
to then convert to a specific type when the direct type assertion is not possible.
- Use
interface
until you run into an issue which type
would solve (an interface is always extendable, and types require using intersections, interfaces can use extends
)
- Unions are their own type unless using
typeof === …
- Literal types are one-possible-value types (constants)
- Literal type unions are extremely useful (e.g.
alignment: "left" | "center" | "right"
)
- Literal types may cause you to have to do things like
method: "GET" as "GET"
, since otherwise method
would’ve been inferred as a string, or to set an entire object as const
to set all properties as literals.
- You can use optional chaining like in Swift:
optionalVariable?.someProp
and optionalVariable!.someProp
- Unique references can be created with
Symbol(string)
- The
!!
operator causes the value to be a literal type true
or false
, not a boolean
- Checking
x ≠ null
is better as it also checks for undefined
. It works the other way around: x == undefined
checks for null
.
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.
- Functions can have properties. For that you must include a call signature with the format
(arg1: Type, arg2: Type2): ReturnType
in the type declaration next to the other properties.
- You can also write custom constructors (constructor signature) with
new (arg: T): SomeClass
in the type declarator of a function.