How to express “function with T as parameter | string which is a key of T” in TypeScript












1














I have the following TypeScript, which does work:



interface Columns {
[s: string]: string | ((item: any) => string);
}

const exportAsCsv = function (data: any, columns: Columns): void {
const header = Object.keys(columns)
.map(x => `"${x}"`)
.join(";");

const rows = ;
for (const item of data) {
const row = Object
.values(columns)
.map(field => typeof field === 'function' ? field(item) : item[field])
.map(x => (x || '').replace(/"/, '""'))
.map(x => `"${x}"`)
.join(";");
rows.push(row);
}
console.log([header, ...rows].join("rn"));
}


The idea is you pass in an array of objects, and a column object where the keys are the headers (can be any string) and the value should be either the name of a property or a function returning a value.



const users = [{id: 1, name: 'Alice', isCool: true}, ...];
const columns = {
'Id': 'id,
'Name': 'name',
'Is cool': u => u.isCool ? 'Yes' : 'No',
};
exportToCsv(users, columns);


This all works, but I'd like stricter typing. The following "works", with the exception that I just can't figure out how to write the Columns type generically. Keep getting stuff not being assignable, type parameters being declared but not used, etc, etc.



interface Columns<T> {
[s: string]: ?;
}
const exportAsCsv = function <T> (data: T, columns: Columns<T>): void


How do I express this properly?










share|improve this question





























    1














    I have the following TypeScript, which does work:



    interface Columns {
    [s: string]: string | ((item: any) => string);
    }

    const exportAsCsv = function (data: any, columns: Columns): void {
    const header = Object.keys(columns)
    .map(x => `"${x}"`)
    .join(";");

    const rows = ;
    for (const item of data) {
    const row = Object
    .values(columns)
    .map(field => typeof field === 'function' ? field(item) : item[field])
    .map(x => (x || '').replace(/"/, '""'))
    .map(x => `"${x}"`)
    .join(";");
    rows.push(row);
    }
    console.log([header, ...rows].join("rn"));
    }


    The idea is you pass in an array of objects, and a column object where the keys are the headers (can be any string) and the value should be either the name of a property or a function returning a value.



    const users = [{id: 1, name: 'Alice', isCool: true}, ...];
    const columns = {
    'Id': 'id,
    'Name': 'name',
    'Is cool': u => u.isCool ? 'Yes' : 'No',
    };
    exportToCsv(users, columns);


    This all works, but I'd like stricter typing. The following "works", with the exception that I just can't figure out how to write the Columns type generically. Keep getting stuff not being assignable, type parameters being declared but not used, etc, etc.



    interface Columns<T> {
    [s: string]: ?;
    }
    const exportAsCsv = function <T> (data: T, columns: Columns<T>): void


    How do I express this properly?










    share|improve this question



























      1












      1








      1







      I have the following TypeScript, which does work:



      interface Columns {
      [s: string]: string | ((item: any) => string);
      }

      const exportAsCsv = function (data: any, columns: Columns): void {
      const header = Object.keys(columns)
      .map(x => `"${x}"`)
      .join(";");

      const rows = ;
      for (const item of data) {
      const row = Object
      .values(columns)
      .map(field => typeof field === 'function' ? field(item) : item[field])
      .map(x => (x || '').replace(/"/, '""'))
      .map(x => `"${x}"`)
      .join(";");
      rows.push(row);
      }
      console.log([header, ...rows].join("rn"));
      }


      The idea is you pass in an array of objects, and a column object where the keys are the headers (can be any string) and the value should be either the name of a property or a function returning a value.



      const users = [{id: 1, name: 'Alice', isCool: true}, ...];
      const columns = {
      'Id': 'id,
      'Name': 'name',
      'Is cool': u => u.isCool ? 'Yes' : 'No',
      };
      exportToCsv(users, columns);


      This all works, but I'd like stricter typing. The following "works", with the exception that I just can't figure out how to write the Columns type generically. Keep getting stuff not being assignable, type parameters being declared but not used, etc, etc.



      interface Columns<T> {
      [s: string]: ?;
      }
      const exportAsCsv = function <T> (data: T, columns: Columns<T>): void


      How do I express this properly?










      share|improve this question















      I have the following TypeScript, which does work:



      interface Columns {
      [s: string]: string | ((item: any) => string);
      }

      const exportAsCsv = function (data: any, columns: Columns): void {
      const header = Object.keys(columns)
      .map(x => `"${x}"`)
      .join(";");

      const rows = ;
      for (const item of data) {
      const row = Object
      .values(columns)
      .map(field => typeof field === 'function' ? field(item) : item[field])
      .map(x => (x || '').replace(/"/, '""'))
      .map(x => `"${x}"`)
      .join(";");
      rows.push(row);
      }
      console.log([header, ...rows].join("rn"));
      }


      The idea is you pass in an array of objects, and a column object where the keys are the headers (can be any string) and the value should be either the name of a property or a function returning a value.



      const users = [{id: 1, name: 'Alice', isCool: true}, ...];
      const columns = {
      'Id': 'id,
      'Name': 'name',
      'Is cool': u => u.isCool ? 'Yes' : 'No',
      };
      exportToCsv(users, columns);


      This all works, but I'd like stricter typing. The following "works", with the exception that I just can't figure out how to write the Columns type generically. Keep getting stuff not being assignable, type parameters being declared but not used, etc, etc.



      interface Columns<T> {
      [s: string]: ?;
      }
      const exportAsCsv = function <T> (data: T, columns: Columns<T>): void


      How do I express this properly?







      typescript






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 '18 at 11:47

























      asked Nov 20 '18 at 11:39









      Svish

      63.4k143381545




      63.4k143381545
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You can ensure the value of Columms is either a key of T or a function accepting T using this type:



          interface Columns<T> {
          [s: string]: keyof T | ((item: T) => string);
          }
          const exportAsCsv = function <T>(data: T, columns: Columns<T>): void {
          //...
          }
          const users = [{ id: 1, name: 'Alice', isCool: true }];
          exportAsCsv(users, {
          'Id': 'id',
          'Name': 'name',
          'Is cool': u => u.isCool ? 'Yes' : 'No',
          });
          exportAsCsv(users, {
          'Id': 'id',
          'Name': 'name2', // error
          'Is cool': u => u.isCooll ? 'Yes' : 'No', //error
          });


          You can also create the columns separately from the call but you need to specify T:



          const users = [{ id: 1, name: 'Alice', isCool: true }];
          const columns : Columns<typeof users[number]> = {
          'Id': 'id',
          'Name': 'name',
          'Is cool': u => u.isCool ? 'Yes' : 'No',
          };
          exportAsCsv(users, columns);





          share|improve this answer

















          • 1




            Ah! There we go! The key was your last note there, that I had to specify the type when I made the columns object. When I hadn't, I got Type 'string' is not assignable to type '"id" | "name" ...'., which is what I didn't understand. 🤦‍♂️ Thank you! 😀
            – Svish
            Nov 20 '18 at 12:25











          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%2f53392222%2fhow-to-express-function-with-t-as-parameter-string-which-is-a-key-of-t-in-ty%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









          1














          You can ensure the value of Columms is either a key of T or a function accepting T using this type:



          interface Columns<T> {
          [s: string]: keyof T | ((item: T) => string);
          }
          const exportAsCsv = function <T>(data: T, columns: Columns<T>): void {
          //...
          }
          const users = [{ id: 1, name: 'Alice', isCool: true }];
          exportAsCsv(users, {
          'Id': 'id',
          'Name': 'name',
          'Is cool': u => u.isCool ? 'Yes' : 'No',
          });
          exportAsCsv(users, {
          'Id': 'id',
          'Name': 'name2', // error
          'Is cool': u => u.isCooll ? 'Yes' : 'No', //error
          });


          You can also create the columns separately from the call but you need to specify T:



          const users = [{ id: 1, name: 'Alice', isCool: true }];
          const columns : Columns<typeof users[number]> = {
          'Id': 'id',
          'Name': 'name',
          'Is cool': u => u.isCool ? 'Yes' : 'No',
          };
          exportAsCsv(users, columns);





          share|improve this answer

















          • 1




            Ah! There we go! The key was your last note there, that I had to specify the type when I made the columns object. When I hadn't, I got Type 'string' is not assignable to type '"id" | "name" ...'., which is what I didn't understand. 🤦‍♂️ Thank you! 😀
            – Svish
            Nov 20 '18 at 12:25
















          1














          You can ensure the value of Columms is either a key of T or a function accepting T using this type:



          interface Columns<T> {
          [s: string]: keyof T | ((item: T) => string);
          }
          const exportAsCsv = function <T>(data: T, columns: Columns<T>): void {
          //...
          }
          const users = [{ id: 1, name: 'Alice', isCool: true }];
          exportAsCsv(users, {
          'Id': 'id',
          'Name': 'name',
          'Is cool': u => u.isCool ? 'Yes' : 'No',
          });
          exportAsCsv(users, {
          'Id': 'id',
          'Name': 'name2', // error
          'Is cool': u => u.isCooll ? 'Yes' : 'No', //error
          });


          You can also create the columns separately from the call but you need to specify T:



          const users = [{ id: 1, name: 'Alice', isCool: true }];
          const columns : Columns<typeof users[number]> = {
          'Id': 'id',
          'Name': 'name',
          'Is cool': u => u.isCool ? 'Yes' : 'No',
          };
          exportAsCsv(users, columns);





          share|improve this answer

















          • 1




            Ah! There we go! The key was your last note there, that I had to specify the type when I made the columns object. When I hadn't, I got Type 'string' is not assignable to type '"id" | "name" ...'., which is what I didn't understand. 🤦‍♂️ Thank you! 😀
            – Svish
            Nov 20 '18 at 12:25














          1












          1








          1






          You can ensure the value of Columms is either a key of T or a function accepting T using this type:



          interface Columns<T> {
          [s: string]: keyof T | ((item: T) => string);
          }
          const exportAsCsv = function <T>(data: T, columns: Columns<T>): void {
          //...
          }
          const users = [{ id: 1, name: 'Alice', isCool: true }];
          exportAsCsv(users, {
          'Id': 'id',
          'Name': 'name',
          'Is cool': u => u.isCool ? 'Yes' : 'No',
          });
          exportAsCsv(users, {
          'Id': 'id',
          'Name': 'name2', // error
          'Is cool': u => u.isCooll ? 'Yes' : 'No', //error
          });


          You can also create the columns separately from the call but you need to specify T:



          const users = [{ id: 1, name: 'Alice', isCool: true }];
          const columns : Columns<typeof users[number]> = {
          'Id': 'id',
          'Name': 'name',
          'Is cool': u => u.isCool ? 'Yes' : 'No',
          };
          exportAsCsv(users, columns);





          share|improve this answer












          You can ensure the value of Columms is either a key of T or a function accepting T using this type:



          interface Columns<T> {
          [s: string]: keyof T | ((item: T) => string);
          }
          const exportAsCsv = function <T>(data: T, columns: Columns<T>): void {
          //...
          }
          const users = [{ id: 1, name: 'Alice', isCool: true }];
          exportAsCsv(users, {
          'Id': 'id',
          'Name': 'name',
          'Is cool': u => u.isCool ? 'Yes' : 'No',
          });
          exportAsCsv(users, {
          'Id': 'id',
          'Name': 'name2', // error
          'Is cool': u => u.isCooll ? 'Yes' : 'No', //error
          });


          You can also create the columns separately from the call but you need to specify T:



          const users = [{ id: 1, name: 'Alice', isCool: true }];
          const columns : Columns<typeof users[number]> = {
          'Id': 'id',
          'Name': 'name',
          'Is cool': u => u.isCool ? 'Yes' : 'No',
          };
          exportAsCsv(users, columns);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 '18 at 12:09









          Titian Cernicova-Dragomir

          57.7k33452




          57.7k33452








          • 1




            Ah! There we go! The key was your last note there, that I had to specify the type when I made the columns object. When I hadn't, I got Type 'string' is not assignable to type '"id" | "name" ...'., which is what I didn't understand. 🤦‍♂️ Thank you! 😀
            – Svish
            Nov 20 '18 at 12:25














          • 1




            Ah! There we go! The key was your last note there, that I had to specify the type when I made the columns object. When I hadn't, I got Type 'string' is not assignable to type '"id" | "name" ...'., which is what I didn't understand. 🤦‍♂️ Thank you! 😀
            – Svish
            Nov 20 '18 at 12:25








          1




          1




          Ah! There we go! The key was your last note there, that I had to specify the type when I made the columns object. When I hadn't, I got Type 'string' is not assignable to type '"id" | "name" ...'., which is what I didn't understand. 🤦‍♂️ Thank you! 😀
          – Svish
          Nov 20 '18 at 12:25




          Ah! There we go! The key was your last note there, that I had to specify the type when I made the columns object. When I hadn't, I got Type 'string' is not assignable to type '"id" | "name" ...'., which is what I didn't understand. 🤦‍♂️ Thank you! 😀
          – Svish
          Nov 20 '18 at 12:25


















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53392222%2fhow-to-express-function-with-t-as-parameter-string-which-is-a-key-of-t-in-ty%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

          "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

          Alcedinidae

          Origin of the phrase “under your belt”?