Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Preferred way of defining objects with all optional members? #16738

@leonard-thieu

Description

@leonard-thieu
  • I have a question that is inappropriate for StackOverflow. (Please ask any appropriate questions there).

This is the typical way of defining an object with all optional members:

interface Options {
    a?: boolean;
    b?: string;
}

However, because all members are optional, TypeScript will allow anything to match:

function init(options: Options) {
    if (typeof options !== 'object') {
        throw new Error();
    }
}

// This isn't an error but is invalid.
init(1);

Alternatively, the object could be defined as:

type StrictOptions = {
    a: boolean;
    b?: string;
} | {
    a?: boolean;
    b: string;
};

and used like:

function strictInit(options: StrictOptions | object) {
    if (typeof options !== 'object') {
        throw new Error();
    }
}

// TypeScript correctly flags this as an error.
strictInit(1);

This results in an error from the compiler as you'd expect but can become very verbose. Would it be preferred to define options objects this way? Is there a more succinct way of doing this?

Edit:
Just realized I could simply define it as:

// All members not optional
interface Options {
    a: boolean;
    b: string;
}

type StrictOptions = Pick<Options, keyof Options>;
function strictInit(options: StrictOptions | object) {
    if (typeof options !== 'object') {
        throw new Error();
    }
}

strictInit(1);                          // Error
strictInit({});                         // OK
strictInit({ a: true });                // OK
strictInit({ b: '' });                  // OK
strictInit({ a: true, b: '' });         // OK
strictInit({ a: true, b: '', c: 1 });   // Error

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions