TypeScript Interface Default Values: Examples
TypeScript Interface Default Values
In TypeScript, interfaces define the structure of objects, specifying their properties and their types. While interfaces themselves don't directly support default values for properties, you can achieve this effect using the optional
property syntax or the Partial
utility type.
Optional Properties:
- Syntax:
interface MyInterface { property1: string; property2?: number; // Optional property }
- Explanation:
- The
?
symbol after a property name indicates that the property is optional. - If an object implementing this interface doesn't provide a value for the optional property, it will be considered undefined.
- The
Partial Utility Type:
- Syntax:
interface MyInterface { property1: string; property2: number; } type PartialMyInterface = Partial<MyInterface>; const myObject: PartialMyInterface = { property1: "value1" };
- Explanation:
- The
Partial
utility type creates a new interface where all properties of the original interface become optional. - You can use this to create objects that only require a subset of the original interface's properties.
- The
Key Points:
- Default Values: While interfaces don't have built-in default values, optional properties and
Partial
provide ways to achieve similar effects. - Optional Properties: Useful when you want to allow objects to omit certain properties without causing errors.
- Partial Utility Type: Useful for creating objects with a subset of required properties.
- Type Safety: Both approaches maintain TypeScript's strong type safety, ensuring that objects created from these interfaces adhere to the defined structure.
interface Person {
name: string;
age?: number; // Optional property
}
const person1: Person = {
name: "Alice",
age: 30
};
const person2: Person = {
name: "Bob"
};
In this example, the age
property is optional. The person1
object includes both name
and age
, while person2
only includes name
.
Using the Partial
Utility Type
interface Product {
name: string;
price: number;
description?: string;
}
type PartialProduct = Partial<Product>;
const product1: PartialProduct = {
name: "Laptop",
price: 999
};
Here, PartialProduct
makes all properties of Product
optional. You can create objects with only a subset of the required properties.
Combining Optional Properties and Partial
interface User {
username: string;
email: string;
address?: {
street: string;
city: string;
zipCode: number;
};
}
const user1: User = {
username: "johnDoe",
email: "[email protected]",
address: {
street: "123 Main St",
city: "Anytown",
zipCode: 12345
}
};
const user2: Partial<User> = {
username: "janeSmith",
email: "[email protected]"
};
This example demonstrates how you can combine optional properties and Partial
to create more flexible interfaces.
- Optional properties: Use
?
to make properties optional. Partial
utility type: Makes all properties of an interface optional.- Flexibility: These techniques provide flexibility in defining object structures.
- Type safety: TypeScript ensures that objects created from these interfaces adhere to the defined structure.
Alternative Methods for TypeScript Interface Default Values
While TypeScript doesn't directly support default values for interface properties, there are several alternative approaches you can employ to achieve similar functionality:
Optional Chaining (?.)
- Purpose: Safely access properties of an object when they might be undefined.
- Example:
interface Person {
name: string;
age?: number;
}
const person: Person = { name: "Alice" };
const age = person?.age || 0; // If age is undefined, use 0 as default
Nullish Coalescing Operator (??)
- Purpose: Provide a default value only if the expression is null or undefined.
interface Product {
price?: number;
}
const product: Product = { };
const price = product.price ?? 100; // If price is undefined or null, use 100 as default
Default Parameters in Functions
- Purpose: Set default values for function arguments.
interface Person {
name: string;
age?: number;
}
function greet(person: Person, age: number = 30) {
console.log(`Hello, ${person.name}! You are ${age} years old.`);
}
Conditional Logic
- Purpose: Check for the existence of properties and provide default values accordingly.
interface User {
email?: string;
}
function sendEmail(user: User) {
const email = user.email || "[email protected]";
// ... send email
}
Class-Based Approach
- Purpose: Use a class to encapsulate default values and provide a more object-oriented approach.
class Person {
constructor(public name: string, public age: number = 30) {}
}
Choosing the Right Method:
- Optional Chaining and Nullish Coalescing: Best for accessing optional properties and providing default values in a concise way.
- Default Parameters: Ideal for functions where default values are frequently needed.
- Conditional Logic: Useful when more complex logic is required to determine the default value.
- Class-Based Approach: Suitable for creating objects with default values and encapsulating related logic.
typescript