-
Notifications
You must be signed in to change notification settings - Fork 0
Optional Properties
Optional properties are properties declared in our type definitions which may not be necessary on every variable created using a custom type created by us.
Let imagine for example that we are creating a type for a user:
- All users must have a username
- All users must have a password
- Not all uses may want to provide their date of birth, but we need our user type to be read to receive this information if the user provides it.
This small scenario shows us a simple example where the use of optional properties are handy.
Keep in mind that optional porperties just have meaning when we are defining custom types in objects - as one should expect, since properties are the keys on the key-value pair that construct and object.
Also, when we make use of optional properties we need really do think a lot if that specific property should whether or not be optional, since declaring a property as optional reduces drastically our type safety.
To create an optional property, all that is required is to add a ? at the front of the property name, before declaring which is the type of this property.
If we use the scenario mentioned before as an example, the optional property "dob" (date of birth) should be declared like in the snippet below:
type User = {
name: string;
pass: string;
dob?: Date;
};
const user1: User = {
name: 'user1',
pass: 'pass1',
dob: new Date('10-10-1990'),
};
const user2: User = {
name: 'user2',
pass: 'pass2',
};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