简体   繁体   English

Function 返回从数组参数中输入的键定义的选择类型

[英]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.我正在尝试创建一个 function ,在其中给它一个泛型,然后将一个数组作为参数,并从泛型类型中选择所需的键。 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.如果有人有解决方案,通用 rest 参数也是可能的。

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.棘手的是,我看到的问题是 Typescript 似乎不允许您部分提供 generics,您要么必须显式提供它们,要么隐含地全部提供它们。 It would be nice to have some syntax like <string, ?>.最好有一些像 <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希望有人可以向我们展示光明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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