Skip to content

Type to invert optionality of properties #16173

Closed as not planned
Closed as not planned
@CzBuCHi

Description

@CzBuCHi

add new mapped type: Invert<T> ... I do not know, how to explain it in english, so i use code:

// proposal syntax
type Invert<T> = {
    [P in keyof T]?: T[P];
    [P? in keyof T]: T[P];
};

// usage
type Original = {
    first: any;
    second?: any;
}

type Inverted = Invert<Original>;

// type Inverted is threated as if declared like this:
type Inverted = {
    first?: any; // first is optional becasue it was required in Original
    second: any; // second is required becasue it was optional in Original
}

example usage: react defaultProps - to ensure, that all optional props are declared.

type SomeProps = {
    name: string;
    point?: { x: number, y: number };
}

class Some extends React.Component<SomeProps, void> {
    // proposal usage
    static defaultProps: Invert<SomeProps> = {
        // here i get compiler error if do not specify property 'point'
    };

    // current usage (worst)
    static defaultProps: any = {
        // here i dont get any errors at all
    };

    // better
    static defaultProps: Partial<SomeProps> = {
        // here i dont get any errors if i dont specify point
        // but at least get compiler error for typo...
    };

    // even better
    static defaultProps: { name?: string; point: { x: number, y: number } } = {
        // here i get compiler error if do not specify property 'point' and for typo
        // but i was forced to create new type ...
    };
}

priority: really low, almost negative :) - but if it can be done and isnt too hard ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions