TypeScript Required Utility Type

📝 Table Of Contents

☕️ Summary

The Required<Type> TypeScript utility type constructs a new type consisting of all properties of Type set to required. If you're following the TypeScript utility types guide, this is the opposite of Partial

Let's continue with our user updating function that uses Partial<Type> in code sandbox. If you haven't followed the guide from the beginning, go back to Partial

We can make a new function to create a user and the Required type is perfect for this!

▶️ Code Sandbox Example

🛠 How It Works

Since we're making a function that will create a new user, we want to make sure the shape of the data matches the User interface.

// User.tsx

export function createUser(user: Required<User>) {
  return { ...user };
}

When calling the createUser function, again, we must pass in every property or T.S. will warn us.

// App.tsx

const user1 = createUser({
  firstName: "Vitalik",
  lastName: "Buterin",
  age: 27,
  favoriteSongs: [
    "Hold On - Moxura",
    "Pressure - Martin Garrix",
    "Run It Up - Lil Tjay",
  ],
});

const user2 = createUser({
  firstName: "Satoshi",
  lastName: "Nakamoto",
  age: 900,
  favoriteSongs: ["Shape of You - Ed Sheeran"],
});

let user3 = createUser({
  firstName: "Lex",
  lastName: "Fridman",
  age: 33,
  favoriteSongs: [
    "Rolling in the Deep - Adele",
    "All About That Bass - Meghan Trainor",
  ],
});

// updateUser function from  Partial<Type> Tutorial :)
user3 = updateUser(user3, { firstName: "Robot" });

const listOfUsers = [user1, user2, user3];

Required<User> will also make every property of User required even if it is set to optional (e.g.) age?: number

Note: This is really where required is useful, you're constructing a new type from a given type that already exists and you can be confident that all properties are required regardless of the given types properties.

🧠 Quiz Question

Given a type Group with 2 optional properties groupName and members:

// User[] is an array of objects of type User from the interface we created

type Group = {
  groupName?: string;
  members?: User[];
};

If we wanted to define a new type StrictGroup with Required<Group> like this:

type StrictGroup = Required<Group>;

Which of the following is true of StrictGroup?

Test your knowledge 🧠