Skip to content

Add support for exactOptionalPropertyTypes: true #5051

@elinfame

Description

@elinfame

Describe the feature you'd love to see
I would like the type definitions to support this stricter TypeScript settings: https://www.typescriptlang.org/tsconfig/#exactOptionalPropertyTypes

With exactOptionalPropertyTypes enabled, TypeScript applies stricter rules around how it handles properties on type or interfaces which have a ? prefix.

For example, this interface declares that there is a property which can be one of two strings: ‘dark’ or ‘light’ or it should not be in the object.

interface UserDefaults {
// The absence of a value represents 'system'
colorThemeOverride?: "dark" | "light";
}

Without this flag enabled, there are three values which you can set colorThemeOverride to be: “dark”, “light” and undefined.

Setting the value to undefined will allow most JavaScript runtime checks for the existence to fail, which is effectively falsy. However, this isn’t quite accurate; colorThemeOverride: undefined is not the same as colorThemeOverride not being defined. For example, "colorThemeOverride" in settings would have different behavior with undefined as the key compared to not being defined.

exactOptionalPropertyTypes makes TypeScript truly enforce the definition provided as an optional property:

const settings = getUserSettings();
settings.colorThemeOverride = "dark";
settings.colorThemeOverride = "light";

// But not:
settings.colorThemeOverride = undefined;
Type 'undefined' is not assignable to type '"dark" | "light"' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the type of the target.

Additional context (optional)
This makes preact hard to use in projects that don't want to give up this setting globally nor use skipLibChecks: True for preact.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions