Skip to content

Conditionally optional/conditionally readonly propertiesΒ #44261

Open

Description

Conditionally-Optional Properties (in object types and interfaces)

πŸ” Search Terms

  • conditionally optional
  • conditional optional
  • conditionally readonly
  • conditional readonly

These issues are related, but not exactly the same:

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion / πŸ“ƒ Motivating Example

A new syntax and associated type-checking making it possible to mark a property as "conditionally-optional", for example:

interface Calculate<T> {
  items: T[];
  
  /**
   * Converts an item into a string for comparison.
   * If `T` is already a string type, this is optional.
   */  
  getKey(? if T extends string): (item: T) => string;
}

the intent here is that getKey is optional if T is string or a subtype of string, but otherwise getKey is mandatory. Thus, an implementation could (for example) provide a default implementation getKey = str => str.

It's currently possible to write types that accomplish this using a mixture of intersections and conditionally-mapped types. However, you lose certain important ergonomic attributes:

  • the syntax for intersection types, mapped types, and conditional types is much more complicated and much less familiar than interface/object types
  • conditional types and complex mappings are likely to lose jsdoc comments, defeating intellisense when developers are later trying to use the type
  • complex types can't be extended whereas interfaces and object types can be

πŸ’» Use Cases

In general, any attribute of a property could be made conditional in the same way:

type Example = <T, Flag extends boolean, Active extends boolean> = {
  // conditionally optional:
  convertToString (? if T extends string): (item: T) => string;

  // optional; made conditionally required:
  initialValue? (-? if T extends boolean): T; 

  // conditionally readonly:
  (readonly if Flag extends "permanent") flagValue: boolean;

  // conditionally defined:
  (parentId if Active extends true): string;
}

In most cases, a basic (but incomplete) workaround exists: use the less-restrictive form everywhere. For example, if it's going to mostly be used and you don't want to forget to pass a property, just make it required; if it's mostly going to be accessed and you don't want to forget that a property is present, just make it optional, etc.

Allowing these values to be set conditionally would just make it easier to express certain more-complex domain-specific constraints, while keeping the types mostly self-contained and readable.

Activity

  1. RyanCavanaugh commented on May 28, 2021

    @RyanCavanaugh
    Member

    This seems at least combinatorially explosive (maybe undecidable?) when performing inference from a concrete type to a Calculate<T>, since you could write something like

    interface Calculate<T> {
      x(? if T extends Calculate<A>): U
      y(? if T extends Calculate<B>): V
    }

    If the answer to that is "In practice there will be very few of these conditions" then it seems like not much is being gained over CalcString | CalcNonString<T>.

  2. Nathan-Fenner commented on May 28, 2021

    @Nathan-Fenner
    Author

    I hadn't considered recursive constraints - for my purposes I certainly wouldn't need those, so just rejecting them would be fine. That would be the same as writing

    type Recursive<T> = Recursive<T> extends { foo : string } ? {foo: T} : number;
    //// ^^^^^^^^^ Type alias 'Recursive' circularly references itself.(2456)

    A specific example that clearly can't be rewritten as just a union would be something like:

    type ForString<T extends string> = {
      value: T;
      render: (item: T) => Result;
      key?: (value: T) => string; // optional
    }
    
    type ForAny<T> = {
      value: T;
      render: (item: T) => Result;
      key: (value: T) => string; // required
    }

    you can't write

    type ForBoth<T> = ForString<T> | ForAny<T>; // Type 'T' does not satisfy the constraint 'string'.(2344)

    and writing

    type ForBoth<T extends string> = ForString<T> | ForAny<T>;

    defeats the purpose of having ForAny.

    So instead you could write

    type ForBoth<T> = T extends string ? ForString<T> : ForAny<T>;

    I can't just use a non-generic ForString because there are also other fields that also refer to T which may be more specific than string (e.g. a union or enum or a tagged template literal type). Or more generically with e.g. objects with certain properties or other constraints.

  3. Nokel81 commented on Mar 30, 2022

    @Nokel81

    I would very much in favour of this feature though for maybe only a subset of this. Currently the solution requires switching to type (instead of interface) which breaks other things.

    My use case is having two "sides" depending on a type parameter.

    For example:

    interface Arguments<Namespaced extends boolean> {
      ...
      namespace(? if Namespaced !extends true): Namespaced extends true
    	? string
    	: Namespaced extends false
          ? undefined
          : string | undefined;
    }
  4. aleclofabbro commented on May 2, 2022

    @aleclofabbro

    also good for :

    export type MayHaveUsefulFoo<MyFoo> = {
      //  ... some other useful props
      foo(? if MyFoo extends undefined | null | void): MyFoo 
    } 

    instead of

    export type MayHaveUsefulFoo<MyFoo> = {
      //  ... some other useful props
    } & (MyFoo extends undefined | null | void
      ? { foo?: MyFoo }
      : { foo: MyFoo })
  5. kasperpeulen commented on Oct 5, 2022

    @kasperpeulen

    The current solutions looks quite ugly indeed.

    export type StoryAnnotations<
      TFramework extends AnyFramework = AnyFramework,
      TArgs = Args,
      TArgsAnnotations extends Partial<TArgs> = Partial<TArgs>
    > = BaseAnnotations<TFramework, TArgs> & {
      /**
       * Override the display name in the UI (CSF v3)
       */
      name?: StoryName;
    
      /**
       * Override the display name in the UI (CSF v2)
       */
      storyName?: StoryName;
    
      /**
       * Function that is executed after the story is rendered.
       */
      play?: PlayFunction<TFramework, TArgs>;
    
      /** @deprecated */
      story?: Omit<StoryAnnotations<TFramework, TArgs>, 'story'>;
    } & ({} extends TArgsAnnotations ? { args?: TArgsAnnotations } : { args: TArgsAnnotations });

    It also forces you to rewrite interfaces into types with intersections.

  6. mhshakouri commented on Jan 24, 2023

    @mhshakouri

    I was looking for something simple, human readable, and also understanable to the naked eye for making a parameter available on a type :

    using your "AVOID instead of" I achieved this:

    export type GlobalApiCallOptions<PARAMS, TYPE, REQBODY> = {
      hooks?: ApiCallHooks<TYPE>
      requestConfig?: AxiosRequestConfig
    } & (PARAMS extends undefined | null | void
      ? {}
      : { params: PARAMS })
      & (REQBODY extends undefined | null | void
      ? {}
      : { requestBody: REQBODY })
    

    ofcourse its for another purpose already, this type it self for me is a type generator for some functions,
    and I wanted to make a better auto suggestions by the IDE and also prevent developers from passing paramteres that they should not in some cases

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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