我找到了型別級別Split函式的定義:
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] };
uj5u.com熱心網友回復:
當然有:
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>}` : "";
如果您想像 Sonic 一樣快,您也可以使用 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;
這里有一個游樂場供你玩耍。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/477921.html
