TypeScript 模板文字数组连接

TypeScript Template literals Array Join

我找到了类型级别的定义 Split function:

type Split<S extends string, D extends string> =
    string extends S ? string[] :
    S extends '' ? [] :
    S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] : [S];

是否还有一种方法可以创建类型级别 Join<string[], string> 函数,以便我可以使用它们将下划线更改为连字符?

例如:

type ChangeHyphensToUnderscore<T> = { [P in keyof T & string as `${Join(Split<P, '-'>, '_')}`]: T[P] };

当然有:

type Stringable = string | number | bigint | boolean | null | undefined;

type Join<A, Sep extends string = ""> = A extends [infer First, ...infer Rest] ? Rest extends [] ? `${First & Stringable}` : `${First & Stringable}${Sep}${Join<Rest, Sep>}` : "";

如果你想和索尼克一样快,你也可以使用 TCO:

type Join<A, Sep extends string = "", R extends string = ""> = A extends [infer First, ...infer Rest] ? Join<Rest, Sep, R extends "" ? `${First & Stringable}` : `${R}${Sep}${First & Stringable}`> : R;

Here's a playground for you to play.