Optional properties allow an object to include a value only when it exists.

Optional Properties

optional.ts
interface Profile {
    name: string;
    nickname?: string;
}

const nicknameValue: string | undefined = ;
const profile: Profile = {
    name: "Grace"
};

if (nicknameValue !== undefined) {
    profile.nickname = nicknameValue;
}

const displayName: string = profile.nickname ?? profile.name;
console.log(`display=${displayName}`);
interface Profile {
    name: string;
    nickname?: string;
}

const nicknameValue: string | undefined = ;
const profile: Profile = {
    name: "Grace"
};

if (nicknameValue !== undefined) {
    profile.nickname = nicknameValue;
}

const displayName: string = profile.nickname ?? profile.name;
console.log(`display=${displayName}`);
interface Profile {
    name: string;
    nickname?: string;
}

const nicknameValue: string | undefined = ;
const profile: Profile = {
    name: "Grace"
};

if (nicknameValue !== undefined) {
    profile.nickname = nicknameValue;
}

const displayName: string = profile.nickname ?? profile.name;
console.log(`display=${displayName}`);
optional property A `?` after a property name means the property may be missing.