简体   繁体   English

Typescript 拆分字符串并验证类型

[英]Typescript split string and validate type

Let's say i have a string value of ReplaceText::some.other.property , I'd like to split this value by the delimeter of :: and validate the types of each input假设我有一个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');

This returns the values, but action is not of type of Action , I'm not quite sure where to begin here!这将返回值,但 action 不是Action类型,我不太确定从哪里开始!

eg, if i did:例如,如果我这样做了:

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

You just need to use a string literal type like:您只需要使用字符串文字类型,例如:

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

Now ActionWithPath is any string that starts with an Action , followed by :: and then any string.现在ActionWithPath是以Action开头的任何字符串,后跟:: ,然后是任何字符串。

Then just use that type as your constraint:然后只需使用该类型作为约束:

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

And the rest works like you expect:其余的就像您期望的那样工作:

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

See playground 看游乐场


Note: deriving a dotted object path is much trickier and out of scope of this question, but you can start here: Typescript: deep keyof of a nested object注意:导出带点的对象路径要复杂得多,超出了这个问题的范围,但你可以从这里开始: Typescript: deep keyof of a nested object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM