October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Tell an Optional TypeScript Property from a Present Key

An optional TypeScript property may be omitted; a property set to undefined is still present. Learn how runtime checks and exactOptionalPropertyTypes distinguish them.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

No. In TypeScript, an optional property may be left out of an object, while a property explicitly set to undefined is present with that value. Reading either one can produce undefined, but the object’s key presence is still distinguishable.

What does an optional property mean?

A question mark after an object property means the property may be omitted. It does not mean that every object has the property with an undefined value, nor does it make a read safe without checking.

As an Amazon Associate I earn from qualifying purchases.

interface Settings {
  colorThemeOverride?: "dark" | "light";
}

const omitted: Settings = {};
const set: Settings = { colorThemeOverride: "dark" };

const theme = omitted.colorThemeOverride; // undefined

The read from omitted evaluates to undefined because no value is available for that key. The type of a read from an optional property accounts for the possibility that the property is missing, so check the result before using it as a definite value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How can you tell an absent key from a present key set to undefined?

At runtime, the two object shapes are different. A missing-property read and a present property containing undefined can yield the same value, but a presence check can tell them apart.

const omitted = {};
const presentUndefined = { colorThemeOverride: undefined };

omitted.colorThemeOverride; // undefined
presentUndefined.colorThemeOverride; // undefined

"colorThemeOverride" in omitted; // false
"colorThemeOverride" in presentUndefined; // true

The in operator checks whether the property exists on the object or its prototype chain. Other operations that inspect or copy enumerable own properties can also reveal a difference: for example, an own enumerable property set to undefined is still a property that can be enumerated or copied, whereas an omitted key is not there to copy. See the TypeScript TSConfig documentation for exactOptionalPropertyTypes.

When does TypeScript allow explicit undefined?

The answer depends on exactOptionalPropertyTypes in the project’s tsconfig.json. TypeScript 4.4 introduced this opt-in setting. It is not included automatically by strict and requires strictNullChecks. The TypeScript 4.4 release notes describe the flag’s exact-write behavior.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
Declaration May omit the key? May write explicit undefined with exact checking? Meaning
p?: T Yes No Omission is allowed; the declared value type is T.
p?: T | undefined Yes Yes Omission and an explicitly present undefined are both allowed.
p: T | undefined No Yes The key must exist, but its value may be undefined.

Without exactOptionalPropertyTypes, TypeScript retains the historical behavior of accepting an explicit undefined assignment to an optional property, effectively treating it as allowed for writes. With the flag enabled, p?: T permits leaving the property out but rejects p: undefined unless undefined appears in T.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
interface ThemeSetting {
  colorThemeOverride?: "dark" | "light";
}

const omitted: ThemeSetting = {}; // valid
const explicit: ThemeSetting = { colorThemeOverride: undefined };
// Accepted when exactOptionalPropertyTypes is off;
// rejected when it is on.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Which declaration should you choose?

Use p?: T when omission is the intended signal

This is appropriate when callers may leave a setting out and your API does not intend to accept a present property whose value is explicitly undefined. Enabling exact optional-property checking makes that write-time distinction enforceable.

Use p?: T | undefined when both states are accepted

Choose this when callers may omit the key or provide it with an explicit undefined. The declaration communicates both possibilities even when exact optional-property checking is enabled.

Use p: T | undefined when the key must always exist

This requires callers to provide the property, while allowing its value to be undefined. It is different from an optional property: an object with no p key does not satisfy the required-property shape.

What should you check in an existing project?

  1. Inspect tsconfig.json. Check whether strictNullChecks and exactOptionalPropertyTypes are enabled. The latter is an independent opt-in setting, so strict alone does not establish that explicit undefined writes are rejected.
  2. Read the property declaration. Distinguish p?: T from p?: T | undefined and p: T | undefined; they express different rules about omission and writes.
  3. Handle reads separately from writes. Even if a declaration disallows writing explicit undefined, an optional property may still be absent. Check for a usable value before relying on it.
  4. Use a presence check when presence itself matters. A value comparison with undefined does not tell you whether the key was omitted. Use a key-presence test such as "p" in object when that distinction is part of the logic.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.