Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 6, 2022 10:07 pm GMT

How the TypeScript Partial Type Works

The Partial type in TypeScript is a utility type which does the opposite of Required. It sets all properties in a type to optional.

Let's look at how it works. If you're interested in the opposite problem, try my article on how the Required type works in TypeScript.

Partial Type in TypeScript

In TypeScript, we can define a type as optional with a ? question mark. For example, in the below code, lastName is optional. Therefore, even though firstUser has the type User, we can leave out lastName as it is not required.

type User = {    firstName: string,    lastName?: string}let firstUser:User = {    firstName: "John"}

Sometimes, the type we inherit or use has no optional types, but we know that in certain circumstances some properties might be missing. Take a look at the following example. Here, lastName is not optional anymore, but firstUser still doesn't have it:

type User = {    firstName: string,    lastName: string}let firstUser:User = {    firstName: "John"}

This code throws an error, since it is expecting that firstUser of type User should have a property called lastName:

Property `lastName` is missing in type `{ firstName: string; }` but required in type `User`.

If we want to avoid that error, we have to change firstUser's type to Partial<User>. That will tell TypeScript to set every property in the type User to optional:

type User = {    firstName: string,    lastName: string}let firstUser:Partial<User> = {    firstName: "John"}

This is ultimately the same as redefining the User type to:

type User = {    firstName?: string,    lastName?: string}

The only difference is, we can now use both - if we want the type to have some missing properties, we can use Partial. If we don't, we can just use the normal User type:

type User = {     firstName: string,     lastName: string }let firstUser:Partial<User> = { firstName: "John" } let secondUser:User = { firstName: "John", lastName: "Doe" }

As with many other utility types in TypeScript, Partial is meant to work with interfaces or custom types defined as objects like our User type above. So it won't work on things like variables.

If you've enjoyed this quick guide, check out more TypeScript content here.


Original Link: https://dev.to/smpnjn/how-the-typescript-partial-type-works-2klj

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To