Code Logo

Typed Optional Config

Published at24 Jul 2026
TypeScript Functions Easy 0 views
Like0

Write a TypeScript function that creates a personalized greeting with optional configuration using typed parameters. The function takes a name (string) and an optional config object with properties: title?: string, formal?: boolean.

Optional properties in TypeScript use the ? modifier: property?: type. The parameter can be undefined or omitted when calling the function. Use default values for missing properties.

This demonstrates TypeScript's optional parameters and interface-like object typing for configuration patterns commonly used in libraries.

Optional properties in TypeScript use the ? modifier, indicating the property may be present or undefined. This pattern is commonly used for configuration objects where most options have defaults.

TypeScript's structural typing allows passing objects with additional properties, making this pattern flexible. Optional chaining (config?.title) or default values (||) safely access potentially undefined properties.

Optional properties use the ? modifier in TypeScript, indicating the property may be present or undefined. This pattern is common for configuration objects where most options have sensible defaults. TypeScript's structural typing allows passing objects with additional properties beyond the defined type.

Example Input & Output

Example 1
Input
"Jane", {"title":"Dr."}
Output
"Hi Dr. Jane!"
Example 2
Input
"John", {}
Output
"Hi John!"
Example 3
Input
"Alex", {"title":"Prof.","formal":true}
Output
"Good day, Prof. Alex!"
Example 4
Input
"Sir", {"formal":true}
Output
"Good day, Mr. Sir!"

Algorithm Flow

Recommendation Algorithm Flow for Typed Optional Config
Recommendation Algorithm Flow for Typed Optional Config

Solution Approach

Define the config parameter type inline: config?: { title?: string; formal?: boolean }. Access config properties with optional chaining or default values using ||.

If formal is true, return 'Good day, Title Name'. If false, return 'Hi Name!'. Use default title 'Mr.' if not provided.

Best Answers

typescript - Approach 1
function greetWithConfig(name: string, config?: { title?: string; formal?: boolean }): string {
    var title = (config && config.title) || 'Mr.';
    if (config && config.formal) return 'Good day, ' + title + ' ' + name + '!';
    if (config && config.title) return 'Hi ' + title + ' ' + name + '!';
    return 'Hi ' + name + '!';
}