Typescript optional field in type

Optional Properties In TypeScript

Optional Properties are those properties that are not mandatory. In the example below the person object name is usually mandatory but age may not be. When we create a person object without assigning a value to age the compiler throws age is missing in a type error. To solve this problem, we need to mark the property as optional.

Creating Optional Properties in TypeScript

To make a specific property optional just add a question mark (?) after the property name

Note that we did not include age in the class constructor function. If you want to include that then make sure you mark it as an optional parameter

Optional Property and Undefined

Adding ? makes age as optional property. Trying to access the value of age returns undefined as expected.

But typescript also allows us to assign undefined value to an optional property although age is of type number .

This is because TypeScript treats every optional property as a union type of undefined and assigned type.

ExactOptionalPropertyTypes Config Option

In the previous section, we showed you that typescript allows us to assign undefined to an optional property.

Читайте также:  Login and Registration Form in HTML

You can stop that by setting the exactOptionalPropertyTypes to true in the tsconfig.json file under the section compilerOptions . Note that you also need to enable strictNullChecks for the exactOptionalPropertyTypes to work.

With exactOptionalPropertyTypes enabled, the TypeScript compiler throws an error when we try to assign the undefined to the age variable.

//Type ‘< name: string; age: undefined; >‘ is not assignable to type ‘Person’ with ‘exactOptionalPropertyTypes: true’. Consider adding ‘undefined’ to the types of the target’s properties.

You can override the behavior by explicitly setting the type as undefined

Make all properties optional of an existing type

Typescript utility types allow us to construct a new type from an existing type. The Partial utility type is one such utility that takes a type and constructs a new type with all the properties set to optional.

The following is the syntax for converting an existing type to optional.

In this example, the Person interface has all properties marked as required. Assigning it an empty object will result in an error.

You can use the Partial to create a new type with all properties set to optional. Hence it will not result in any compiler error.

The following is one of the use cases for the Partial utility type.

The updatePerson function updates the subset of the properties of person object. The second argument to fields: Partial create fields object with a type of Person interface with all properties set to optional. This allows us to pass any combination arguments to updatePerson . It also provides a strong type of checking as we cannot pass a non-existing property.

Источник

How To Make An Optional Property In TypeScript?

Tim Mouskhelichvili

When developing a TypeScript project, developers often need to make a property optional inside an interface, type, or class. Luckily, this is easy to do.

To mark a property as optional in TypeScript, you can place a question mark after the property name.

This article explains optional properties in TypeScript and shows multiple code examples.

typescript optional property

Making a property optional

By default, a property in TypeScript is required. If you don’t pass a value to a required property, TypeScript’s compiler will throw an error.

typescripttype Animal = < name: string; age: number; > const cow: Animal = < name: 'Cow', age: 4 >;

Both the name AND the age properties are required. You will get an error if you omit to pass a value for one of them.

If you want to make one of those properties optional, add a question mark after the property name you want to make optional.

typescripttype Animal = < name: string; age?: number; > const cow: Animal = < name: 'Cow' >;

The age property is now optional, AND when we don’t pass a value to it, the compiler doesn’t complain. If you try to access the age property, you will get undefined .

P.S. You can pass undefined to any optional property in TypeScript. Indeed, TypeScript treats an optional property as a union type of its type AND undefined .

Making a property optional inside an interface

To mark a property as optional inside an interface, place a question mark after the property name.

typescriptinterface IPerson < name: string; age?: number; >

In this example, the age property is optional.

The best Web Development course in 2023! 👉 Learn Web Development

Making a property optional inside a class

To mark a property as optional inside a class, place a question mark after the class property name.

typescriptclass Animal < private name: string; private age?: number; public constructor(name: string, age?:number) < this.name = name; this.age = age; > >

In this example, the age class property is optional.

Final thoughts

As you can see, marking a property as optional is simple in TypeScript.

Just add a question mark after the property name.

If you need to make all properties inside a type optional, use the partial utility type.

typescript optional property

Here are some other TypeScript tutorials for you to enjoy:

The best Web Development course in 2023! 👉 Learn Web Development

Tim Mouskhelichvili

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.

Источник

Optional Properties In TypeScript

Optional Properties are those properties that are not mandatory. In the example below the person object name is usually mandatory but age may not be. When we create a person object without assigning a value to age the compiler throws age is missing in a type error. To solve this problem, we need to mark the property as optional.

Creating Optional Properties in TypeScript

To make a specific property optional just add a question mark (?) after the property name

Note that we did not include age in the class constructor function. If you want to include that then make sure you mark it as an optional parameter

Optional Property and Undefined

Adding ? makes age as optional property. Trying to access the value of age returns undefined as expected.

But typescript also allows us to assign undefined value to an optional property although age is of type number .

This is because TypeScript treats every optional property as a union type of undefined and assigned type.

ExactOptionalPropertyTypes Config Option

In the previous section, we showed you that typescript allows us to assign undefined to an optional property.

You can stop that by setting the exactOptionalPropertyTypes to true in the tsconfig.json file under the section compilerOptions . Note that you also need to enable strictNullChecks for the exactOptionalPropertyTypes to work.

With exactOptionalPropertyTypes enabled, the TypeScript compiler throws an error when we try to assign the undefined to the age variable.

//Type ‘< name: string; age: undefined; >‘ is not assignable to type ‘Person’ with ‘exactOptionalPropertyTypes: true’. Consider adding ‘undefined’ to the types of the target’s properties.

You can override the behavior by explicitly setting the type as undefined

Make all properties optional of an existing type

Typescript utility types allow us to construct a new type from an existing type. The Partial utility type is one such utility that takes a type and constructs a new type with all the properties set to optional.

The following is the syntax for converting an existing type to optional.

In this example, the Person interface has all properties marked as required. Assigning it an empty object will result in an error.

You can use the Partial to create a new type with all properties set to optional. Hence it will not result in any compiler error.

The following is one of the use cases for the Partial utility type.

The updatePerson function updates the subset of the properties of person object. The second argument to fields: Partial create fields object with a type of Person interface with all properties set to optional. This allows us to pass any combination arguments to updatePerson . It also provides a strong type of checking as we cannot pass a non-existing property.

Источник

Оцените статью