- Published on
TypeScript, optional & undefined
- Authors
- Name
- Kieran Hauser
TypeScript is a popular programming language that adds static type checking to JavaScript. When working with TypeScript, you may encounter the terms optional and undefined. In this article, we'll explain the uses and differences between these two terms.
Optional Types
In TypeScript, an optional type is denoted with a ?
character. An optional type indicates that a value may be present or may be undefined
. For example, consider the following interface:
interface Person {
name: string;
age?: number;
}
In this interface, the age
property is optional, which means it may or may not be present. You can still access the age
property, but TypeScript will raise a warning if you try to access it without first checking if it exists.
function printPerson(person: Person) {
console.log(person.name);
// Check if age exists before saccessing it
if (person.age) {
console.log(person.age);
}
}
Undefined Type
In TypeScript, the undefined
type is used to represent a value that is not defined. For example, consider the following code:
let name: string;
console.log(name); // undefined
In this example, the name
variable is not assigned a value, so its value is undefined
. If you try to access a property of an object that is undefined
, TypeScript will raise an error.
const person = { name: 'John' };
console.log(person.age); // Error: Property 'age' does not exist on type '{ name: string; }'.
In this example, the person
object does not have an age
property, so TypeScript raises an error when you try to access it.
Differences
The main difference between optional
and undefined
is that optional
indicates that a value may be present or may be undefined
, while undefined
indicates that a value is not defined. In other words, optional
means that a value is optional, while undefined
means that a value is not present.
For example, if you have a function that takes an optional argument, you can call it with or without the argument:
function printName(name?: string) {
console.log(name || 'World');
}
printName(); // World
printName('John'); // John
In this example, the name
parameter is optional, so you can call the function with or without the name
argument.
If you have a function that takes a required argument, you must call it with the argument:
function printAge(age: number) {
console.log(age);
}
printAge(); // Error: Expected 1 arguments, but got 0.
printAge(undefined); // Error: Argument of type 'undefined' is not assignable to parameter of type 'number'.
In this example, the age
parameter is required, so you must call the function with the age
argument.
Conclusion
In summary, optional
and undefined
are both used to indicate that a value may or may not be present. However, optional
means that a value is optional, while undefined
means that a value is not defined. By understanding the differences between these two terms, you can use them effectively in your TypeScript code.