-
Notifications
You must be signed in to change notification settings - Fork 0
Custom Types
After having a basic idea on how to properly use basic types on a TypeScript codebase, it's time to have a glance on how to create custom types to be used on your code.
By convention those are created using the type keyword and the name given to type should always start with a capital leterm just like provide in the snippet below.
type CustomType = string;By doing this, we can use the CustomTypecreated above to declare other variables, like so:
let text: CustomType = 'Some text';Keep in mind though that creating custom types over basic types can not comy handy, those are more useful when creating "union types" (more about this later) and objects.
For the sake of exemplification lets assume that we are working with a person object, fored by 3 properties: name, age and isAdult.
let person1 = {
name: 'Joe',
age: 18,
isAdult: true,
};The question is, how would we create a type that describes the person object? The anwser to that relies on working with custom types.
To create a custom type for the person object referenced above, we should add the following type definition on our code and then use it when declaring variables that are of the type person:
type Person = {
name: string;
age: number;
isAdult: boolean;
};
let person1: Person = {
name: 'Joe',
age: 18,
isAdult: true,
};
let person2: Person = {
name: 'Mary',
age: 18,
// the line below will trigger a potential error, because the type Person does not expect isadult as a property, but isAdult
isadult: true,
};Those notes were written while watching the tutorial videos while taking the classes from the online course Learn TypeScript on Scrimba.
Because english is not my mother language, they can contain some typos and everything written here is based on my understanding about the discussed topics and may not be 100% accurate.
If you want the full course, support the instructor by buying their course on Scrimba.
- Home
- Introduction
- Introduction to TypeScript
- The Pizza Application
- Move to TypeScript
- Defensive Coding
- Typing variables
- Typing Pizza App: part 1
- Custom types
- Typing Pizza App: part 2
- Nested Object types
- Optional Properties
- Typing Pizza App: part 3
- Array Types
- Typing Pizza App: part 4
- Literal Types
- Unions
- Typing Pizza App: part 5
- Typing Pizza App: part 6
- Typing Pizza App: part 7
- Returning Types
- Typing Pizza App: part 8
- Any Type
- Typing Pizza App: part 9
- Utility Types
- Typing Pizza App: part 10
- Generics
- Typing Pizza App: part 11