w3resource

TypeScript Mapped Type: Making properties optional

TypeScript Advance Types: Exercise-11 with Solution

Write a TypeScript program that creates a TypeScript mapped type called 'Optional'. This mapped type should take an object type as a parameter and make all its properties optional. Test the mapped type with an example object.

Sample Solution:

TypeScript Code:

// Define an example object type with required properties
type Student = {
  name: string;
  age: number;
  email: string;
};

// Define a mapped type 'Optional' that makes all properties optional
type Optional = {
  [K in keyof T]?: T[K];
};

// Create an example object of type 'Student'
const student: Student = {
  name: "Mira Brigitta",
  age: 22,
  email: "[email protected]",
};

// Use the 'Optional' mapped type to make the properties optional
type OptionalStudent = Optional;

// Create an instance of the 'OptionalStudent' type
const optionalStudent: OptionalStudent = {
  name: "Mira", // You can provide some properties
  age: 22,
};

// Print the modified object
console.log(optionalStudent);

Explanations:

In the exercise above -

  • First, we start by defining an example object type called "Student" with three required properties: 'name', 'age', and 'email'.
  • Next, we define a mapped type called "Optional" that takes a generic type parameter 'T'. Within the mapped type, we use a mapped type transformation to iterate over the keys (K) of the input type (T). For each property, we add the ? symbol to make it optional.
  • Create an instance of the "Student" type called ‘student’.
  • Use the "Optional" mapped type to create a new type called "OptionalStudent", which makes all properties optional.
  • Next we create an instance of the "OptionalStudent" type called "optionalStudent". Here, you can see that we've only provided the 'name' property, as the rest are now optional.

Output:

// [object Object] 
{
  "name": "Mira",
  "age": 22
}

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript generic swap function example.
Next: TypeScript mapped type example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/typescript-exercises/typescript-advance-types-exercise-11.php