TypeScript Basics: JavaScript with Types
Basic Types
In this lesson you will
- Use string, number, boolean, arrays and tuples
- Handle null and undefined safely
- Explain why unknown is safer than any
Introduction
TypeScript's type system starts with the same kinds of values JavaScript has. In this lesson you meet them, and the two special types you should use carefully.
The primitive types
The three you will use most are lower case: string, number and boolean.
Always write them in lower case. String with a capital letter is a different, rarely wanted type.
Arrays
An array type says what is inside. Write the element type followed by []:
You may also see Array<number>, which means the same thing.
Quick quiz
Which type describes a list of text values?
Tuples
A tuple is an array with a fixed length and a known type at each position.
Tuples are handy when a function returns two related values.
null and undefined
undefined means "no value has been set" and null means "deliberately empty". With TypeScript's strict mode, which these lessons use, you must say when a value might be missing, by using a union with |:
Why does this matter? In JavaScript, calling a method on a missing value crashes with "Cannot read properties of undefined". TypeScript catches this at compile time:
To fix it, check first. Inside the if, TypeScript knows text is a string:
This is called narrowing, and you will see more of it in lesson 5.
Quick quiz
Why does text.toUpperCase() fail when text has the type string | undefined?
any and unknown
Sometimes you really do not know the type, for example when reading JSON from a server.
anyturns type checking off for that value. TypeScript will let you do anything with it, so mistakes sneak back in.unknownsays "I don't know yet". TypeScript makes you check the value before you use it.
Compare:
Prefer unknown over any. Treat any as a last resort.
Try it yourself
The code below has two type errors. Fix both so that it prints 6.
Summary
- Use lower case
string,numberandboolean. number[]is an array of numbers. A tuple such as[string, number]fixes length and order.- Say when a value can be missing with
string | undefined, then check before using it. - Prefer
unknowntoany, becauseunknownforces a check.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading