1.1: Types
TypeScript, just like JavaScript, accepts different units of data. Things like strings, numbers, booleans...stuff you're all used to by now. The difference now is we need to be explicit in what unit of data is going into the variable.
Setting the type is a snap in TypeScript. Just place the type after a :
and you're good to go! Let's take a look at the different types.
BOOLEANS
At this point, we know that booleans are simple true/false statements:
STRINGS
TypeScript uses single or double quotes for string data, just like in JavaScript:
Template strings may also be used in Typescript:
NUMBERS
Numbers in TypeScript are floating value points, which are numbers with fractional parts (for example, 3.65). TypeScript also accepts hexadecimal, binary, and octal literals:
ARRAYS
Array types can be written in two different ways:
or as an generic array type:
TUPLES
These are arrays with with mixed types and a limited number of items. Tuples have to be a string and a number:
Please note, order is important! So if you indicate numbers are first in the array, then they HAVE to be first or you will get an error.
ENUMS
Enums are a TypeScript feature that makes numbers more expressive. By default, enums start at number 0:
ANY
Occasionally, we may not know what type of variables when we are creating our applications. We can use any
to allow for any type of data to get set in the variable.
VOID
Void could almost be considered the opposite of any. We see void
used as the return type of functions that do not return a value:
Declaring void
on a variable is not the most useful practice, because we can only assign undefined
or null
to them. In fact, undefined
and null
are there own types:
NEVER
Never represents a value that will never occurs. We usually see never
with functions that have an unreachable end point:
FUNCTION TYPES
Types can be added to the arguments as well as the return type of the function:
We can use arrow functions as well:
TYPE INFERENCE
TypeScript can use type inference to provide information on the type when there is no explicit annotation. For example:
TypeScript now assumes that the variable marathonMan
is of the type string
. If we tried to set it to anything else, we would get an error. This works, but since we are writting in TypeScript for Anuglar, let's get in the habit of being explicit with our types.
adapted from TypeScript Documentation and Understanding TypeScript by Maximilian Schwarzmüller
NEXT SECTION
Last updated