问题:TypeScriptTyping中数组、元组参数转换为StringUnion后在函数中使用的问题

StackOverFlow

坐等大佬回答

https://stackoverflow.com/questions/71389353/how-to-convert-inferred-string-tuple-to-string-union-in-typescript-typings

目标

我想实现:

//dispatch 参数类型
export type Dispatch<ActionType> = (action: ActionType) => void;

let spareCheck = createTaskDispatcher(["spare","not_spare"], (ctx, payload, dispatch) => {
  //这里的Dispatch的参数是 "spare"|"not_spare"的string union类型
  dispatch("not_spare");
});
目标

但是我在尝试了多种办法都无法实现,比如使用:

type ArrayRetreiver<A> = A extends Array<infer W> ? W : never;

但是我直接在函数中使用时,可能是我函数构造或者其他问题,无法实现,dispatch参数ActionTypes是stirng类型。

还有使用Tuple来操作,也是只得到了sting类型或者直接无法解析出来。

妥协实现

在尝试我已知的方法无法实现后,我将数组类型改为了string类型,而后用一个SplitString类型将对应的condition分割开后作为dispatch的参数,这样倒是实现了目的,但是我还是觉得不是很方便。

export type Dispatch<ActionType> = (action: ActionType) => void;
type SplitString<S, Separater extends string = "|", AL = never> = S extends `${infer A}${Separater}${infer Rest}` ? SplitString<Rest, Separater, AL | A> : S | AL;
function createTaskDispatcher<C, P, U extends string>(conditionList: U, dispatcher: (ctx: C, payload: P, dispath: Dispatch<SplitString<U>>) => void) {
}
let spareCheck = createTaskDispatcher("spare|not_spare", (ctx, payload, dispatch) => {
  dispatch("not_spare");
});

疑惑点

我最主要无法理解的是使用上述的ArrayRetriever将字符串数组提取后应该是形成了 `spare|not_spare` 类型的string union,但在传入Dispatch<ArrayRetriever<U>>就变成了string类型。

上面这个是我最无法理解的地方,我觉得是我对TypeScript的类型推断理解还不足,后面补一下。


v1.0 wep 添加问题基本描述和妥协解决

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注