[英]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) => {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.