Dynamically determine second argument when the first argument is a key from an interface The Next CEO of Stack OverflowTypescript: How to define interface for dynamical object like thisConvert a list of key-value-pair interfaces into a single mapped typeUsing generic keyof for a set action, for both the key and its typeTypeScript. How to use not exported type definitions?Post FormData (key, value): controller not receiving value when stringGeneric interface for conversion [keys].option.value.number to option.[Keys].numberTypescript clarification on index types and mapped typesTypeScript Interface With Known and Unknown Keys Not Using `any`Require child object property value to be same type as parent keyIs it possible to generate a string-enum in typescript with random or same strings?

sp_blitzCache results Memory grants

I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin

Rotate a column

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?

How to avoid supervisors with prejudiced views?

Does it take more energy to get to Venus or to Mars?

How do we know the LHC results are robust?

Sending manuscript to multiple publishers

Preparing Indesign booklet with .psd graphics for print

Why do airplanes bank sharply to the right after air-to-air refueling?

Inappropriate reference requests from Journal reviewers

Is 'diverse range' a pleonastic phrase?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

What's the best way to handle refactoring a big file?

WOW air has ceased operation, can I get my tickets refunded?

How to start emacs in "nothing" mode (`fundamental-mode`)

Why has the US not been more assertive in confronting Russia in recent years?

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

What does convergence in distribution "in the Gromov–Hausdorff" sense mean?

Novel about a guy who is possessed by the divine essence and the world ends?

What flight has the highest ratio of time difference to flight time?

How does the Z80 determine which peripheral sent an interrupt?

Complex fractions

How to prevent changing the value of variable?



Dynamically determine second argument when the first argument is a key from an interface



The Next CEO of Stack OverflowTypescript: How to define interface for dynamical object like thisConvert a list of key-value-pair interfaces into a single mapped typeUsing generic keyof for a set action, for both the key and its typeTypeScript. How to use not exported type definitions?Post FormData (key, value): controller not receiving value when stringGeneric interface for conversion [keys].option.value.number to option.[Keys].numberTypescript clarification on index types and mapped typesTypeScript Interface With Known and Unknown Keys Not Using `any`Require child object property value to be same type as parent keyIs it possible to generate a string-enum in typescript with random or same strings?










0















I have an interface like so that's passed as options to a module factory function:



interface FactoryOpts 
name?: string
radius?: number
// many more entries...



For example:



factory( radius: 10 )


Then I have an interface that defines the returned value from the factory. It has a few functions, but the one I'm stuck on is called "option" and can't see how I can avoid using "any":



interface ReturnedFactoryInstance 
// I don't want to use "any" for the value, but I also don't
// want to write a method for each options
option(name: keyof FactoryOpts, value: any) => void


interface Factory String, options: FactoryOpts): ReturnedFactoryInstance



Is it possible to dynamically determine the type of value? For example:



const instance = factory( radius: 10 )

// Correct - this will compile
factory.option('radius', 10)

// Error - this will not compile
factory.option('radius', 'some string')


Is the only way to achieve this by making a function for each entry in FactoryOpts?



Solution using Karol's advice:



interface FactoryOpts 
name?: string
radius?: number
// many more entries...


interface Factory
someProps: string
(selector: HTMLElement

interface ReturnedFactoryInstance<ValidOptions>
option: <Key extends keyof ValidOptions>(property: Key, value: ValidOptions[Key]) => void



You can then export a Factory e.g declare const f: Factory etc.










share|improve this question




























    0















    I have an interface like so that's passed as options to a module factory function:



    interface FactoryOpts 
    name?: string
    radius?: number
    // many more entries...



    For example:



    factory( radius: 10 )


    Then I have an interface that defines the returned value from the factory. It has a few functions, but the one I'm stuck on is called "option" and can't see how I can avoid using "any":



    interface ReturnedFactoryInstance 
    // I don't want to use "any" for the value, but I also don't
    // want to write a method for each options
    option(name: keyof FactoryOpts, value: any) => void


    interface Factory String, options: FactoryOpts): ReturnedFactoryInstance



    Is it possible to dynamically determine the type of value? For example:



    const instance = factory( radius: 10 )

    // Correct - this will compile
    factory.option('radius', 10)

    // Error - this will not compile
    factory.option('radius', 'some string')


    Is the only way to achieve this by making a function for each entry in FactoryOpts?



    Solution using Karol's advice:



    interface FactoryOpts 
    name?: string
    radius?: number
    // many more entries...


    interface Factory
    someProps: string
    (selector: HTMLElement

    interface ReturnedFactoryInstance<ValidOptions>
    option: <Key extends keyof ValidOptions>(property: Key, value: ValidOptions[Key]) => void



    You can then export a Factory e.g declare const f: Factory etc.










    share|improve this question


























      0












      0








      0








      I have an interface like so that's passed as options to a module factory function:



      interface FactoryOpts 
      name?: string
      radius?: number
      // many more entries...



      For example:



      factory( radius: 10 )


      Then I have an interface that defines the returned value from the factory. It has a few functions, but the one I'm stuck on is called "option" and can't see how I can avoid using "any":



      interface ReturnedFactoryInstance 
      // I don't want to use "any" for the value, but I also don't
      // want to write a method for each options
      option(name: keyof FactoryOpts, value: any) => void


      interface Factory String, options: FactoryOpts): ReturnedFactoryInstance



      Is it possible to dynamically determine the type of value? For example:



      const instance = factory( radius: 10 )

      // Correct - this will compile
      factory.option('radius', 10)

      // Error - this will not compile
      factory.option('radius', 'some string')


      Is the only way to achieve this by making a function for each entry in FactoryOpts?



      Solution using Karol's advice:



      interface FactoryOpts 
      name?: string
      radius?: number
      // many more entries...


      interface Factory
      someProps: string
      (selector: HTMLElement

      interface ReturnedFactoryInstance<ValidOptions>
      option: <Key extends keyof ValidOptions>(property: Key, value: ValidOptions[Key]) => void



      You can then export a Factory e.g declare const f: Factory etc.










      share|improve this question
















      I have an interface like so that's passed as options to a module factory function:



      interface FactoryOpts 
      name?: string
      radius?: number
      // many more entries...



      For example:



      factory( radius: 10 )


      Then I have an interface that defines the returned value from the factory. It has a few functions, but the one I'm stuck on is called "option" and can't see how I can avoid using "any":



      interface ReturnedFactoryInstance 
      // I don't want to use "any" for the value, but I also don't
      // want to write a method for each options
      option(name: keyof FactoryOpts, value: any) => void


      interface Factory String, options: FactoryOpts): ReturnedFactoryInstance



      Is it possible to dynamically determine the type of value? For example:



      const instance = factory( radius: 10 )

      // Correct - this will compile
      factory.option('radius', 10)

      // Error - this will not compile
      factory.option('radius', 'some string')


      Is the only way to achieve this by making a function for each entry in FactoryOpts?



      Solution using Karol's advice:



      interface FactoryOpts 
      name?: string
      radius?: number
      // many more entries...


      interface Factory
      someProps: string
      (selector: HTMLElement

      interface ReturnedFactoryInstance<ValidOptions>
      option: <Key extends keyof ValidOptions>(property: Key, value: ValidOptions[Key]) => void



      You can then export a Factory e.g declare const f: Factory etc.







      typescript typescript-typings






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 21 at 20:04







      Evan Shortiss

















      asked Mar 21 at 17:01









      Evan ShortissEvan Shortiss

      1,093715




      1,093715






















          1 Answer
          1






          active

          oldest

          votes


















          2














          interface Factory<T> 
          option<K extends keyof T>(this: Factory<T>, name: K, value: T[K]): void;


          type FactoryConstructor = <T>(arg: T) => Factory<T>;


          Usage:



          declare const factory: FactoryConstructor;

          factory( radius: 10 ).option('radius', 1);


          See TypeScript Playground.






          share|improve this answer


















          • 1





            Thank you! This answer is really close! In my case "this" isn't applicable, but the rest is. Updated the question with the solution for this specific case.

            – Evan Shortiss
            Mar 21 at 20:01











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285637%2fdynamically-determine-second-argument-when-the-first-argument-is-a-key-from-an-i%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          interface Factory<T> 
          option<K extends keyof T>(this: Factory<T>, name: K, value: T[K]): void;


          type FactoryConstructor = <T>(arg: T) => Factory<T>;


          Usage:



          declare const factory: FactoryConstructor;

          factory( radius: 10 ).option('radius', 1);


          See TypeScript Playground.






          share|improve this answer


















          • 1





            Thank you! This answer is really close! In my case "this" isn't applicable, but the rest is. Updated the question with the solution for this specific case.

            – Evan Shortiss
            Mar 21 at 20:01















          2














          interface Factory<T> 
          option<K extends keyof T>(this: Factory<T>, name: K, value: T[K]): void;


          type FactoryConstructor = <T>(arg: T) => Factory<T>;


          Usage:



          declare const factory: FactoryConstructor;

          factory( radius: 10 ).option('radius', 1);


          See TypeScript Playground.






          share|improve this answer


















          • 1





            Thank you! This answer is really close! In my case "this" isn't applicable, but the rest is. Updated the question with the solution for this specific case.

            – Evan Shortiss
            Mar 21 at 20:01













          2












          2








          2







          interface Factory<T> 
          option<K extends keyof T>(this: Factory<T>, name: K, value: T[K]): void;


          type FactoryConstructor = <T>(arg: T) => Factory<T>;


          Usage:



          declare const factory: FactoryConstructor;

          factory( radius: 10 ).option('radius', 1);


          See TypeScript Playground.






          share|improve this answer













          interface Factory<T> 
          option<K extends keyof T>(this: Factory<T>, name: K, value: T[K]): void;


          type FactoryConstructor = <T>(arg: T) => Factory<T>;


          Usage:



          declare const factory: FactoryConstructor;

          factory( radius: 10 ).option('radius', 1);


          See TypeScript Playground.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 21 at 17:40









          Karol MajewskiKarol Majewski

          4,3191216




          4,3191216







          • 1





            Thank you! This answer is really close! In my case "this" isn't applicable, but the rest is. Updated the question with the solution for this specific case.

            – Evan Shortiss
            Mar 21 at 20:01












          • 1





            Thank you! This answer is really close! In my case "this" isn't applicable, but the rest is. Updated the question with the solution for this specific case.

            – Evan Shortiss
            Mar 21 at 20:01







          1




          1





          Thank you! This answer is really close! In my case "this" isn't applicable, but the rest is. Updated the question with the solution for this specific case.

          – Evan Shortiss
          Mar 21 at 20:01





          Thank you! This answer is really close! In my case "this" isn't applicable, but the rest is. Updated the question with the solution for this specific case.

          – Evan Shortiss
          Mar 21 at 20:01



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285637%2fdynamically-determine-second-argument-when-the-first-argument-is-a-key-from-an-i%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript