Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make second generic parameter optional in typescript

I’m in trouble with using typescript generic

here is my issue:

I have interface ‘Column’ and makeColumn function to make new column
I wanna set only first generic (UserModel), accessor must be keyof UserModel, and finally get the property of name in the render property

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

here is what I did :

  class UserModel{
    name!:{
      firstName:string;
      secondName:string;
    }
    job!:string
  }
  
  
  
  interface Column<T ,U extends keyof T> {
    accessor: U;
    render: (value: T[U]) => void;
  }

  function makeColumn<T,U extends keyof T >(column: Column<T,U>) {
    return column;
  }

  makeColumn<UserModel>({
    accessor: 'name',
    render: (value) => {
      console.log(value.)
    }
  })

Note: I don’t wanna send a second generic to access the name property (I want it to handle it per se)

Playground

>Solution :

I don’t believe this is possible without currying because it requires partial type inference, something that isn’t supported yet in TypeScript.

function makeColumn<T>() {
    return <U extends keyof T = keyof T>(column: Column<T, U>) => {
        return column;
    };
}

makeColumn<UserModel>()({
    accessor: "name",
    render: (value) => {
        console.log(value.firstName);
    },
});

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading