简体   繁体   中英

Function to return picked types defined from the keys entered in array argument

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM