TypeScript Optional Properties Type
Last Updated :
02 Sep, 2024
TypeScript Opional properties type provides a way of defining the parts that are not necessarily required.
TypeScript Optional Properties Types
- Optional Properties are properties that are not required mandatorily and can be omitted when not needed.
- In TypeScript, you can define optional properties in an interface, in a class, in an object, or in a type by using the '?' modifier after the property name.
- Optional properties allow to specify that a property may or may not be present on an object of that type.
- Optional Properties can be useful when not all properties are required.
Syntax
propertyName? : type;
Parameters
- propertyName: Name of the property that can be optional
- type: Type of the property
- ?: Symbol which specifies that it is an optional property
Optional properties in TypeScript can be specified using different methods which are as follows:
Method 1: Optional properties in Interface
In TypeScript interfaces optional properties can be defined by using the '?' modifier after the property name. This indicates that a property may or may not be present on objects of that interface type.
Example: In the above example,the properties name and age are required but the property designation is optional.
JavaScript
interface Employee {
name: string;
designation?: string; // Optional property
age: number;
}
const employee1: Employee = {
name: "John",
age: 30,
};
const employee2: Employee = {
name: "Jessica",
designation: "Developer",
age: 25,
};
console.log(employee1);
console.log(employee2);
Output:
{ name: 'John', age: 30 }
{ name: 'Jessica', designation: 'Developer', age: 25 }
Mehtod 2: Optional properties in Class
To make a property optional in a class, you can initialize it with undefined in the constructor and mark it as optional in the class definition using the '?' modifier.
Example: In the above example,the property brand is required but the property model is optional.
JavaScript
class Car {
brand: string;
model?: string; // Optional property
constructor(brand: string, model?: string) {
this.brand = brand;
this.model = model;
}
}
const car1 = new Car("Toyota");
const car2 = new Car("Ford", "Focus");
console.log(car1);
console.log(car2);
Output:
Car { brand: 'Toyota', model: undefined }
Car { brand: 'Ford', model: 'Focus' }
Method 3: Optional properties in Type
Type aliases allow you to define optional properties in a similar way to interfaces, using the '?' modifier.
Example: In this example,the properties userId and name are required but the property email is optional.
JavaScript
type User = {
userId: number;
name: string;
email?: String; // Optional property
};
const user1: User = {
userId: 1001,
name: "Anne",
email: "[email protected]",
};
const user2: User = {
userId: 1002,
name: "Smith",
};
console.log(user1);
console.log(user2);
Output:
{ userId: 1001, name: 'Anne', email: '[email protected]' }
{ userId: 1002, name: 'Smith' }
Method 4: Optional properties in Object Literal
Only in interfaces and classes optional properties are allowed and not in object literals. But we can use optional properties in object literals by specifying that the property is optional in the type definition.
Example: In the above example,the properties name and id are required but the property email is optional.
JavaScript
let userAccount1:
{ name: string, id: number, email?: string } = {
name: 'John Smith',
id: 31
};
let userAccount2:
{ name: string, id: number, email?: string } = {
name: 'John Smith',
id: 31,
email: "[email protected]"
};
console.log(userAccount1);
console.log(userAccount2);
Output:
{ name: 'John Smith', id: 31 }
{ name: 'John Smith', id: 31, email: '[email protected]' }
Method 5: Partial Utility
In TypeScript, Partial type is a utility type that allows us to set all properties of an existing type optional. This utility is useful while working with APIs which consists of a lot of properties but only few of them are required.
Syntax:
Partial<existingType>;
Here,
- Partial : 'Partial' is the keyword used to set all properties of existingType as Optional.
- existingType : existingType is the name of already existing interface or type alias.
Example:
JavaScript
type User = {
firstName: string,
lastName: string
}
let firstUser: Partial<User> =
{ firstName: "John" }
let secondUser: User =
{ firstName: "John", lastName: "Doe" }
console.log(firstUser);
console.log(secondUser);
Output:
{ firstName: 'John' }
{ firstName: 'John', lastName: 'Doe' }
Method 6: Using Default Parameter Values
In TypeScript, you can utilize default parameter values to specify optional properties within functions or constructors. This approach can be particularly useful when you need optional properties within function parameters or constructor arguments.
- Specify default parameter values for optional properties within functions or constructors.
- Utilize the defined default parameter values to handle optional properties within functions or constructors.
Example: In this example we are following above explained approach.
JavaScript
// Define a function with optional properties using default parameter values
function createUser(name: string, age: number, designation: string = 'Employee') {
return {
name,
age,
designation,
};
}
// Create users with different optional properties
const user1 = createUser('GFG', 23);
const user2 = createUser('Nikunj', 22, 'Developer');
console.log(user1);
console.log(user2);
Output:
{ name: 'GFG', age: 23, designation: 'Employee' }
{ name: 'Nikunj', age: 22, designation: 'Developer' }
Similar Reads
TypeScript Object Type Optional Properties
In TypeScript, optional properties are denoted using the ? modifier after the property name in the object type definition. This means that when an object is created, the optional property can either be provided or omitted. Syntax:type TypeName = { propertyName: PropertyType; optionalPropertyName?: O
3 min read
How to Specify Optional Properties in TypeScript?
TypeScript is a powerful programming language that extends JavaScript by adding optional static typing and class-based object-oriented programming. One of the key features of TypeScript is the ability to specify optional properties in interfaces and classes, providing flexibility to our object types
3 min read
TypeScript Optional Parameters
Optional parameters in TypeScript allow functions to be called without specifying all arguments, enhancing flexibility and code readability. Denoted by appending a ? to the parameter name.Optional parameters must follow the required parameters in function definitions.Syntaxfunction functionName(para
3 min read
Optional Property Class in TypeScript
TypeScript is an Object Oriented Programming language that allows you to create classes with optional properties which may or may not be assigned with a value. We will discuss two different ways of creating optional property classes in TypeScript: Table of Content By using the Question Mark(?)By ass
4 min read
TypeScript Parameter Type Annotations
TypeScript Parameter type annotations are used to specify the expected data types of function parameters. They provide a way to explicitly define the types of values that a function expects as arguments. Parameter type annotations are part of TypeScript's static typing system, and they help catch ty
2 min read
TypeScript Object Type readonly Properties
In TypeScript, the readonly modifier ensures that a property can be assigned a value only once during initialization and cannot be changed thereafter. This immutability helps prevent accidental modifications to object properties, enhancing code reliability.You can apply readonly to properties in cla
3 min read
TypeScript Less Common Primitives Type
TypeScript Less Common Primitives Type offers a rich set of primitive types to represent data. While most developers are familiar with types like number, string, boolean, and symbol, TypeScript also provides less common primitive types that can be incredibly useful in specific scenarios. These are s
2 min read
TypeScript Conditional Types
In TypeScript, conditional types enable developers to create types that depend on a condition, allowing for more dynamic and flexible type definitions. They follow the syntax T extends U ? X : Y, meaning if type T is assignable to type U, the type resolves to X; otherwise, it resolves to Y.Condition
4 min read
TypeScript Assertions Type
TypeScript Assertions Type, also known as Type Assertion, is a feature that lets developers manually override the inferred or expected type of a value, providing more control over type checking in situations where TypeScript's automatic type inference may not be sufficient. Syntax let variableName:
2 min read
TypeScript Interfaces Type
TypeScript Interfaces Type offers an alternative method for defining an object's type, allowing for a distinct naming approach. Syntax:interface InterfaceName { property1: type1; property2?: type2; readonly property3: type3; // ... method1(): returnType1; method2(): returnType2; // ...}Parameters:in
2 min read