One of the best advantages of using TypeScript is its ability to do static type checking. It helps with code readability and spotting bugs earlier in the development process.
In TypeScript, data is passed with TypeScript objects, usually by an interface or a type that contains all the object's properties. TypeScript gives the developer the ability to modify properties and make one optional.
To create an optional property in TypeScript, use a question mark after the property name like so:
interface IPerson {
name: string;
age?: number;
}
const person: IPerson = {
name: 'Tim'
};
In this example, the age
property is optional, so we don't have to provide its value in the person
object. If you try to access the age
property value, it is going to be undefined
.
The TypeScript compiler will not trigger an error when you do not specify an optional property's value. Even whenstrictNullChecks
is set to true.
Optional parameters in functions
In TypeScript, you can make a function argument optional as well.
const getAge = (age?: number): string => {
return String(age);
};
// This works.
const age = getAge();
// Outputs: "undefined"
console.log(age);
An optional parameter is undefined
.
Note: If a function accepts more than one argument, the optional parameter needs to be last.
Default values
If you provide a default value to a function's argument, it will be automatically optional.
const getAge = (age = 0): string => {
return String(age);
};
// This also works.
const age = getAge();
// Outputs: "0"
console.log(age);
For interfaces, read more here: "How To Set Up A TypeScript Interface Default Value?"
Optional parameter destructuring
You can destruct an optional parameter, like so:
const getAge = ({ age }: { name: string, age?: number }): string => {
return String(age);
};
const age = getAge({ name: 'Tim'});
// Outputs: "undefined"
console.log(age);
However, it is a better practice to provide the destructed parameter with a default value:
const getAge = ({ age = 0 }: { name: string, age?: number }): string => {
return String(age);
};
const age = getAge({ name: 'Tim'});
// Outputs: "0"
console.log(age);
Optional property vs undefined
The difference between the optional property and setting up a property type as undefined
is that you don't have to provide the argument for optional properties.
const getName = (name?: string): string => {
return String(name).toLowerCase();
};
const getName2 = (name: string | undefined): string => {
return String(name).toLowerCase();
};
// This works.
getName();
// You need to pass undefined for this to work.
getName2(undefined);
Note: Generally, I prefer never to pass
undefined
as an argument. I like to usenull
.
undefined
means that something hasn't been initialized.null
implies that something is unavailable.
Final thoughts
Here you have it. You now know how to make an optional property in TypeScript.
Here are some of my other TypeScript tutorials for you to enjoy: