繁体   English   中英

如何动态地将泛型数组的值推断为 TypeScript 中的联合?

[英]How to dynamically infer a the values of a generic array as a union in TypeScript?

鉴于以下声明:

declare function useStrings<T extends string[]>(
  arr: T,
  fn: (item: T extends Array<infer U> ? U : never) => void
): void;

我希望fn中的item参数是T值的联合类型。

然而,当像这样调用时, item被输入为一个字符串:

useStrings(["a", "b", "c"], (item) => {});
//                           ^^^^ string

以下示例给出了预期的结果,但当然不是理想的解决方案:

useStrings(["a", "b", "c"] as ("a" | "b" | "c")[], (item) => {});
//                                                  ^^^^ "a" | "b" | "c"

如何在不诉诸诸如上一个示例中的 hacky 断言的情况下将item推断为 union?

expr as const会将其降低为最窄的元组类型,因此您应该使用它并扩展您的 function 以与只读 arrays 一起使用:

declare function useStrings<T extends readonly string[]>(
  arr: T,
  fn: (item: T extends readonly (infer U)[] ? U : never) => void
): void;

useStrings(["a", "b", "c"] as const, (item) => {});

游乐场链接

我不使用推断,我的解决方案有效。 自己试试吧!

declare function useStrings<T extends string>(
    arr: T[],
    fn: (item: T) => void
): void;

可能不使用推断

暂无
暂无

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

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