Typescript拆分字符串并验证类型



假设我有一个字符串值ReplaceText::some.other.property,我想把这个值除以::的分隔符,并验证每个输入

的类型
type Action = 'ReplaceText' | 'ReplaceImage';
type Split<S extends string, D extends string> =
string extends S ? Action[] :
S extends '' ? [] :
S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] : [S];

declare function translate<P extends string>(path: P): Split<P, '::'>;
const [action, dotString] = translate('ReplaceText::some.other.property');

这返回值,但动作不是类型的Action,我不太确定从哪里开始这里!

例如,如果我做了:

const [action, dotString] = translate('ActionThatDoesNotExist::some.other.property');
// id expect validation errors because this action does not exist!

您只需要使用字符串文字类型,如:

type Action = 'ReplaceText' | 'ReplaceImage';
type ActionWithPath = `${Action}::${string}`

现在ActionWithPath是任何以Action开头的字符串,后跟::,然后是任何字符串。

然后使用该类型作为约束:

declare function translate<P extends ActionWithPath>(path: P): Split<P, '::'>;

其余部分如你所愿:

translate('ReplaceText::some.other.property'); // fine
translate('ActionThatDoesNotExist::some.other.property'); // error

看到操场


注意:派生一个带点的对象路径要复杂得多,并且超出了这个问题的范围,但是你可以从这里开始:

最新更新