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.
>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" }