TypeScript Basics: JavaScript with Types
Object Types and Type Aliases
In this lesson you will
- Write an object type with required, optional and readonly properties
- Name a type with a type alias or an interface
- Type arrays of objects
Introduction
Most real data is an object: a user, a product, a lesson. TypeScript lets you describe the shape of an object, which properties it has and what type each one is. Then typos like user.nmae become errors instead of silent undefined values.
Object types
TypeScript checks every property you read or write. Misspell one and you find out immediately.
Optional and readonly properties
- A
?after a property name makes it optional. readonlymeans it can be set when the object is made, but not changed afterwards.
Quick quiz
What does a ? after a property name, like nickname?: string, mean?
Type aliases
Writing the same object type again and again is tiring. A type alias gives a type a name, using type. By convention names start with a capital letter.
An alias can name any type, not just objects:
Interfaces
An interface is another way to name an object shape. For simple objects it works the same:
Which should you use? For now, either is fine. A common guideline: use interface for object shapes that other code might extend, and type for everything else, such as unions. The next course covers the differences.
Arrays of objects
Combine an alias with [] to type a list of objects. The array methods then know what is inside.
Hover-style help in editors shows names is string[]. TypeScript worked that out from item.name.
Quick quiz
What is the type of cart in const cart: Product[] = [...]?
Try it yourself
Create a type alias Book with a title (string), an author (string), a pages (number) and an optional isbn (string). Then fix the three books so that they match, and print the total number of pages.
Summary
- An object type lists property names and types:
{ name: string; age: number }. ?marks a property optional, andreadonlystops it being changed.typeandinterfaceboth give a shape a reusable name.Product[]types a list of objects, and array methods then know their contents.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading