Junior — Middle
In what situations should the undefined type be used in TypeScript?
sobes.tech AI
Answer from AI
In TypeScript, the undefined type is used to denote variables or properties that are explicitly not assigned a value. It is used in the following situations:
- When a variable may be uninitialized.
- To indicate the absence of a value other than
null. - In functions that may not return a value (for example, returning
voidorundefined). - When working with optional parameters or properties that may be missing.
Example:
function greet(name?: string): string {
if (name === undefined) {
return "Hello, guest!";
}
return `Hello, ${name}!`;
}
Here, name can be undefined if the argument is not provided.