如何在 Typescript 中定义正则表达式匹配的字符串类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51445767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:32:28  来源:igfitidea点击:

How to define a regex-matched string type in Typescript?

regextypescripttypestyping

提问by Our_Benefactors

Is it possible to define an interface which has some information on the format of a string? Take the following example:

是否可以定义一个接口,其中包含有关字符串格式的一些信息?以下面的例子为例:

interface timeMarkers{
    markerTime: string[]        
};

an example would be:

一个例子是:

{
   markerTime: ["0:00","1:30", "1:48"]                   
}

My question: Is there a way to define the type for markerTimesuch that that the string value must always match this regex, instead of declaring it as simply string[]and going from there?

我的问题:有没有办法定义类型以便markerTime字符串值必须始终匹配这个正则表达式,而不是简单地声明它string[]并从那里开始?

var reg = /[0-9]?[0-9]:[0-9][0-9]/;

var reg = /[0-9]?[0-9]:[0-9][0-9]/;

回答by Titian Cernicova-Dragomir

There is no way to define such a type. There is a proposalon GitHub to support this, but it currently does not appear to be a priority. Vote on it and maybe the team might include it in a future release.

没有办法定义这样的类型。GitHub 上有一项支持此功能的提案,但目前似乎不是优先事项。对它进行投票,也许团队可能会将它包含在未来的版本中。

回答by Markus Faatz

I was just looking for a similar feature right now, too!

我现在也在寻找类似的功能!

And I ended up thinking about this: Would'nt it be possible to get this running by setting up a little more complex dev-environment? Maybe you could use a file-watcher to trigger tsc and look up TypeError events to update your *d.ts file.

我最终想到了这一点:是否可以通过设置更复杂的开发环境来运行它?也许您可以使用文件观察器来触发 tsc 并查找 TypeError 事件以更新您的 *d.ts 文件。

I mean something like:

我的意思是这样的:

export type superRegexType = 'type-1' | 'type-2' | '/type-/';

and as a hook something (rudimental suggestion):

并作为一个钩子(基本建议):

const onTypeError = (err: Error, nameOfTypeSuperRegexType: string) => {
  const myTypesFile = require('fs').readFileSync(`path/to/\*d.ts`) as string;
  const searchFor = `export type ${nameOfTypeSuperRegexType} =`;
  const getDefinition = (inMyTypesFile: string, searchFor: string) => {
    const typeDefinitionString = inMyTypesFile.split(searchFor)[0].split(';')[0] + ';';
    const stringsInThere = typeDefinitionString.split(' | ').map(_str => _str.trim());
    const myRegexStr = stringsInThere.pop();
    return {
      oldTypeDefinitionString: typeDefinitionString,
      stringsInThere,
      myRegexStr,
      myRegex: new RegExp(myRegexStr)
    };
  };
  const myTypeDefinition = getDefinition(myTypesFile, searchFor);

  const shouldDynamicallyAddType = myTypeDefinition.myRegex.exec(err.message);
  if (!shouldDynamicallyAddType) {
    console.log("this is a real TypeError");
    console.error(err);
    return;
  } else {
    const indexInErrMessage = shouldDynamicallyAddType.index;
    const _endIdx = err.message.indexOf('\'');
    const typeToAdd = err.message.slice(indexInErrMessage, _endIdx).trim();
    myTypeDefinition.stringsInThere.push(typeToAdd);
    const updatedTypeDefinitionString = `${searchFor} ${myTypeDefinition.stringsInThere.join(' | ')} ${myTypeDefinition.myRegexStr};`;
    myTypesFile.replace(myTypeDefinition.oldTypeDefinitionString, updatedTypeDefinitionString);
    // --> save that new d.ts and return hopefully watch the lint-error disappearing
  }
}

Maybe this kind of solution would allow you to dynamically add types based on your RegEx on compiletime.

也许这种解决方案允许您在编译时根据您的 RegEx 动态添加类型。

What do you think?

你怎么认为?