Basic types
Basic (primitive) types in JavaScript are String
, Number
, Boolean
, null
, undefined
, and Symbol
.
Types in TypeScript add couple more: any
, void
, and never
. Let's add some types to the code!
The any
type is the default value for any variable or argument: this behaves exactly like JavaScript.
Unions
The last one is quite fun: the variable can only have one particular value, everything else will throw an error. Let's make this useful:
Now the eventType
variable can only have one of the two values. This is called a union type and can be used with all types:
Built-in types
There is some more complex built-in types that we can use:
Arrays
It's also possible to tell TypeScript that we expect an array of some elements:
We can also provide types for individual elements in an array (tuple
types):
Tuples require an exact number of elements at exact positions.
Custom types
We can declare custom types using the type
keyword:
And then use them in same way as any other type:
Resources
Last updated