Reputation: 3884
So I think I'm out of luck with this one, but I thought I would give it a shot here before dropping the idea.
I'm trying to create a function where you give it a generic, and then an array as an argument with the wanted keys to pick from the generic type. Something like this.
type Test = {
a: boolean;
b: boolean;
c: boolean;
};
const t = use<Test>(["a", "b"]);
t.a = true;
t.b = true;
t.c = true; // `use` shall not let c be available. This should throw a typescript build error
Generic rest parameters are also a possibility if someone has a solution for that.
use<Test, "a" | "b">(["a", "b"]);
is the only solution I've found that worked so far, but it's really ugly.
Upvotes: 0
Views: 134
Reputation: 783
Tricky, the problem as I see it is that Typescript doesn't seem to let you partially supply generics, you either have to provide them all explicitly or get them all implicitly. It would be nice to have some syntax like <string, ?>. Here is the best I can do
function use<Q, S extends keyof Q>(
q: Q,
properties: S[]
): {
[K in S]: Q[K];
} {
return {} as any;
}
type Test = {
a: boolean;
b: boolean;
c: boolean;
};
const t = use(<Test>null, ["a", "b"]);
Alternatively (I think this is better)
function use<Q>(): <S extends keyof Q>(p: S[]) => { [K in S]: Q[K] } {
return {} as any;
}
type Test = {
a: boolean;
b: boolean;
c: boolean;
};
const t = use<Test>()(["a", "b"]);
Hopefully someone can show us the light
Upvotes: 2