Enforce key and value types of non-indexed members









up vote
1
down vote

favorite












I have a function which can take any object literal so long as all of the values in the object are strings:



function getFirstLetters(obj: [key: string]: string ): string 
return Object.keys(obj).map(key => obj[key][0]);



This works well for any indexed type, the problem arises when I try to use non-indexed objects:



interface SomeData 
user: string;
loc: string;


const someData: SomeData =
user: "coolGuy42",
loc: "New York",
;

function getFirstLetters(obj: [key: string]: string ): string
return Object.keys(obj).map(key => obj[key][0]);


// Argument of type 'SomeData' is not
// assignable to parameter of type
// ' [key: string]: string; '.
// Index signature is missing in type 'SomeData'.
getFirstLetters(someData);


The error is straightforward - I have specifically requested that the function validate obj based on it having an index signature, NOT on the type of its values alone.



Is there any way to make my function work with all objects with a uniform value type without asking anyone who uses it to include an index signature in their interface?










share|improve this question

























    up vote
    1
    down vote

    favorite












    I have a function which can take any object literal so long as all of the values in the object are strings:



    function getFirstLetters(obj: [key: string]: string ): string 
    return Object.keys(obj).map(key => obj[key][0]);



    This works well for any indexed type, the problem arises when I try to use non-indexed objects:



    interface SomeData 
    user: string;
    loc: string;


    const someData: SomeData =
    user: "coolGuy42",
    loc: "New York",
    ;

    function getFirstLetters(obj: [key: string]: string ): string
    return Object.keys(obj).map(key => obj[key][0]);


    // Argument of type 'SomeData' is not
    // assignable to parameter of type
    // ' [key: string]: string; '.
    // Index signature is missing in type 'SomeData'.
    getFirstLetters(someData);


    The error is straightforward - I have specifically requested that the function validate obj based on it having an index signature, NOT on the type of its values alone.



    Is there any way to make my function work with all objects with a uniform value type without asking anyone who uses it to include an index signature in their interface?










    share|improve this question























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I have a function which can take any object literal so long as all of the values in the object are strings:



      function getFirstLetters(obj: [key: string]: string ): string 
      return Object.keys(obj).map(key => obj[key][0]);



      This works well for any indexed type, the problem arises when I try to use non-indexed objects:



      interface SomeData 
      user: string;
      loc: string;


      const someData: SomeData =
      user: "coolGuy42",
      loc: "New York",
      ;

      function getFirstLetters(obj: [key: string]: string ): string
      return Object.keys(obj).map(key => obj[key][0]);


      // Argument of type 'SomeData' is not
      // assignable to parameter of type
      // ' [key: string]: string; '.
      // Index signature is missing in type 'SomeData'.
      getFirstLetters(someData);


      The error is straightforward - I have specifically requested that the function validate obj based on it having an index signature, NOT on the type of its values alone.



      Is there any way to make my function work with all objects with a uniform value type without asking anyone who uses it to include an index signature in their interface?










      share|improve this question













      I have a function which can take any object literal so long as all of the values in the object are strings:



      function getFirstLetters(obj: [key: string]: string ): string 
      return Object.keys(obj).map(key => obj[key][0]);



      This works well for any indexed type, the problem arises when I try to use non-indexed objects:



      interface SomeData 
      user: string;
      loc: string;


      const someData: SomeData =
      user: "coolGuy42",
      loc: "New York",
      ;

      function getFirstLetters(obj: [key: string]: string ): string
      return Object.keys(obj).map(key => obj[key][0]);


      // Argument of type 'SomeData' is not
      // assignable to parameter of type
      // ' [key: string]: string; '.
      // Index signature is missing in type 'SomeData'.
      getFirstLetters(someData);


      The error is straightforward - I have specifically requested that the function validate obj based on it having an index signature, NOT on the type of its values alone.



      Is there any way to make my function work with all objects with a uniform value type without asking anyone who uses it to include an index signature in their interface?







      typescript






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 9 at 20:54









      Sandy Gifford

      2,4821639




      2,4821639






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          You can make the function generic and require the input parameter to be any type whose known properties are all strings:



          function getFirstLetters<T extends Record<keyof T, string>>(obj: T): string 
          return Object.keys(obj).map(key => obj[key][0]); // error



          But the compiler (rightly) complains that it doesn't know what obj[key] might be. After all, the known keys of T are string-valued, but types in TypeScript are not exact. A value of type foo: string might have any number of extra properties. We know that its foo property is a string, but for all we know it might have a bar property that's a number.



          If you are sure that only exact-like types will be passed to getFirstLetters, then you can use a type assertion to convince the compiler that you are doing something safe:



          function getFirstLetters<T extends Record<keyof T, string>>(obj: T): string 
          // no error now
          return (Object.keys(obj) as (Array<keyof T>)).map(key => obj[key][0]);



          And it should work as you expect when you call it:



          getFirstLetters(someData); // no error


          And it will reject values with known properties whose values are not strings:



          getFirstLetters(a: "a", b: 23); // error on b, not a string


          But again, keep in mind that you can pass it some things with unknown non-string properties that will cause problems at runtime:



          const whoopsie: SomeData = Object.assign(, someData, oops: null );
          // whoopsie is a SomeData with an extra "oops" property that the
          // compiler has explicitly forgotten about

          getFirstLetters(whoopsie); // no compiler error
          // but calls null[0] at runtime and explodes!! 💥


          It's up to you if you care about those edge cases and how to deal with them if so. Anyway, hope that helps. Good luck!






          share|improve this answer




















          • huh... so this certainly solves the above problem, but not my actual problem (I simplified it a bunch with a function for brevity). I'll have to rephrase in a separate question.
            – Sandy Gifford
            Nov 12 at 15:31










          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',
          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%2f53233145%2fenforce-key-and-value-types-of-non-indexed-members%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








          up vote
          1
          down vote



          accepted










          You can make the function generic and require the input parameter to be any type whose known properties are all strings:



          function getFirstLetters<T extends Record<keyof T, string>>(obj: T): string 
          return Object.keys(obj).map(key => obj[key][0]); // error



          But the compiler (rightly) complains that it doesn't know what obj[key] might be. After all, the known keys of T are string-valued, but types in TypeScript are not exact. A value of type foo: string might have any number of extra properties. We know that its foo property is a string, but for all we know it might have a bar property that's a number.



          If you are sure that only exact-like types will be passed to getFirstLetters, then you can use a type assertion to convince the compiler that you are doing something safe:



          function getFirstLetters<T extends Record<keyof T, string>>(obj: T): string 
          // no error now
          return (Object.keys(obj) as (Array<keyof T>)).map(key => obj[key][0]);



          And it should work as you expect when you call it:



          getFirstLetters(someData); // no error


          And it will reject values with known properties whose values are not strings:



          getFirstLetters(a: "a", b: 23); // error on b, not a string


          But again, keep in mind that you can pass it some things with unknown non-string properties that will cause problems at runtime:



          const whoopsie: SomeData = Object.assign(, someData, oops: null );
          // whoopsie is a SomeData with an extra "oops" property that the
          // compiler has explicitly forgotten about

          getFirstLetters(whoopsie); // no compiler error
          // but calls null[0] at runtime and explodes!! 💥


          It's up to you if you care about those edge cases and how to deal with them if so. Anyway, hope that helps. Good luck!






          share|improve this answer




















          • huh... so this certainly solves the above problem, but not my actual problem (I simplified it a bunch with a function for brevity). I'll have to rephrase in a separate question.
            – Sandy Gifford
            Nov 12 at 15:31














          up vote
          1
          down vote



          accepted










          You can make the function generic and require the input parameter to be any type whose known properties are all strings:



          function getFirstLetters<T extends Record<keyof T, string>>(obj: T): string 
          return Object.keys(obj).map(key => obj[key][0]); // error



          But the compiler (rightly) complains that it doesn't know what obj[key] might be. After all, the known keys of T are string-valued, but types in TypeScript are not exact. A value of type foo: string might have any number of extra properties. We know that its foo property is a string, but for all we know it might have a bar property that's a number.



          If you are sure that only exact-like types will be passed to getFirstLetters, then you can use a type assertion to convince the compiler that you are doing something safe:



          function getFirstLetters<T extends Record<keyof T, string>>(obj: T): string 
          // no error now
          return (Object.keys(obj) as (Array<keyof T>)).map(key => obj[key][0]);



          And it should work as you expect when you call it:



          getFirstLetters(someData); // no error


          And it will reject values with known properties whose values are not strings:



          getFirstLetters(a: "a", b: 23); // error on b, not a string


          But again, keep in mind that you can pass it some things with unknown non-string properties that will cause problems at runtime:



          const whoopsie: SomeData = Object.assign(, someData, oops: null );
          // whoopsie is a SomeData with an extra "oops" property that the
          // compiler has explicitly forgotten about

          getFirstLetters(whoopsie); // no compiler error
          // but calls null[0] at runtime and explodes!! 💥


          It's up to you if you care about those edge cases and how to deal with them if so. Anyway, hope that helps. Good luck!






          share|improve this answer




















          • huh... so this certainly solves the above problem, but not my actual problem (I simplified it a bunch with a function for brevity). I'll have to rephrase in a separate question.
            – Sandy Gifford
            Nov 12 at 15:31












          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          You can make the function generic and require the input parameter to be any type whose known properties are all strings:



          function getFirstLetters<T extends Record<keyof T, string>>(obj: T): string 
          return Object.keys(obj).map(key => obj[key][0]); // error



          But the compiler (rightly) complains that it doesn't know what obj[key] might be. After all, the known keys of T are string-valued, but types in TypeScript are not exact. A value of type foo: string might have any number of extra properties. We know that its foo property is a string, but for all we know it might have a bar property that's a number.



          If you are sure that only exact-like types will be passed to getFirstLetters, then you can use a type assertion to convince the compiler that you are doing something safe:



          function getFirstLetters<T extends Record<keyof T, string>>(obj: T): string 
          // no error now
          return (Object.keys(obj) as (Array<keyof T>)).map(key => obj[key][0]);



          And it should work as you expect when you call it:



          getFirstLetters(someData); // no error


          And it will reject values with known properties whose values are not strings:



          getFirstLetters(a: "a", b: 23); // error on b, not a string


          But again, keep in mind that you can pass it some things with unknown non-string properties that will cause problems at runtime:



          const whoopsie: SomeData = Object.assign(, someData, oops: null );
          // whoopsie is a SomeData with an extra "oops" property that the
          // compiler has explicitly forgotten about

          getFirstLetters(whoopsie); // no compiler error
          // but calls null[0] at runtime and explodes!! 💥


          It's up to you if you care about those edge cases and how to deal with them if so. Anyway, hope that helps. Good luck!






          share|improve this answer












          You can make the function generic and require the input parameter to be any type whose known properties are all strings:



          function getFirstLetters<T extends Record<keyof T, string>>(obj: T): string 
          return Object.keys(obj).map(key => obj[key][0]); // error



          But the compiler (rightly) complains that it doesn't know what obj[key] might be. After all, the known keys of T are string-valued, but types in TypeScript are not exact. A value of type foo: string might have any number of extra properties. We know that its foo property is a string, but for all we know it might have a bar property that's a number.



          If you are sure that only exact-like types will be passed to getFirstLetters, then you can use a type assertion to convince the compiler that you are doing something safe:



          function getFirstLetters<T extends Record<keyof T, string>>(obj: T): string 
          // no error now
          return (Object.keys(obj) as (Array<keyof T>)).map(key => obj[key][0]);



          And it should work as you expect when you call it:



          getFirstLetters(someData); // no error


          And it will reject values with known properties whose values are not strings:



          getFirstLetters(a: "a", b: 23); // error on b, not a string


          But again, keep in mind that you can pass it some things with unknown non-string properties that will cause problems at runtime:



          const whoopsie: SomeData = Object.assign(, someData, oops: null );
          // whoopsie is a SomeData with an extra "oops" property that the
          // compiler has explicitly forgotten about

          getFirstLetters(whoopsie); // no compiler error
          // but calls null[0] at runtime and explodes!! 💥


          It's up to you if you care about those edge cases and how to deal with them if so. Anyway, hope that helps. Good luck!







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 10 at 0:58









          jcalz

          20.3k21535




          20.3k21535











          • huh... so this certainly solves the above problem, but not my actual problem (I simplified it a bunch with a function for brevity). I'll have to rephrase in a separate question.
            – Sandy Gifford
            Nov 12 at 15:31
















          • huh... so this certainly solves the above problem, but not my actual problem (I simplified it a bunch with a function for brevity). I'll have to rephrase in a separate question.
            – Sandy Gifford
            Nov 12 at 15:31















          huh... so this certainly solves the above problem, but not my actual problem (I simplified it a bunch with a function for brevity). I'll have to rephrase in a separate question.
          – Sandy Gifford
          Nov 12 at 15:31




          huh... so this certainly solves the above problem, but not my actual problem (I simplified it a bunch with a function for brevity). I'll have to rephrase in a separate question.
          – Sandy Gifford
          Nov 12 at 15:31

















           

          draft saved


          draft discarded















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53233145%2fenforce-key-and-value-types-of-non-indexed-members%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

          Use pre created SQLite database for Android project in kotlin

          Darth Vader #20

          Ondo