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

Generic optional function parameter return type

Given this factory

const index = <PK extends string, SK extends string>(pk: PK, sk: SK) => ({ pk, sk });
const i1 = index("pk1"); // type of i1 should be { pk: "pk1" }
const i2 = index("pk1", "sk1"); //  type of i2 should be { pk: "pk1", sk: "sk1" }

I would like to extends this so sk becomes optional and based on whether sk param is provided the return type will be { pk: PK } or { sk: SK }

The optional part is what makes this tricky.

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

>Solution :

Function overloading will let you do that.

You can’t do this with arrow functions to the best of my knowledge – as you can’t redeclare const, which you need for arrow functions.

You can try normal function syntax though.

function index<PK extends string, SK extends string>(
  pk: PK
): {
  pk: PK;
};
function index<PK extends string, SK extends string>(
  pk: PK,
  sk: SK
): {
  pk: PK;
  sk: SK;
};
function index<PK extends string, SK extends string>(pk: PK, sk?: SK) {
  return { pk, sk };
}

const i1 = index("pk1"); // type of i1 should be { pk: "pk1" }
const i2 = index("pk1", "sk1"); //  type of i2 should be { pk: "pk1", sk: "sk1" }

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