【问题标题】:Typescript argument check against a union type针对联合类型的打字稿参数检查
【发布时间】:2019-11-05 19:14:17
【问题描述】:

我想检查一个字符串是否有一个匹配联合类型的前缀,例如:

type Prefix = "ABC" | "DEF" | "GHI" ...;
const hasPrefix = (str: string): boolean => {
   // I want to check the first 3 characters of the string
   // And see if it matches any of the Prefix
   // Something like
   //  if (str.substr(0, 3) === Prefix)
}

【问题讨论】:

  • 我想问题是如何将Prefix类型与内置方法一起使用,对吧?似乎只有自定义逻辑(如您的评论)适用(输入字符串,然后检查)。
  • 为什么要检查类型而不是前缀字符串数组?你的用例是什么?

标签: javascript typescript


【解决方案1】:

在当前版本的 TypeScript 中,您无法剖析联合类型。对于您的问题,我会推荐一种使用 enums 的方法,如下所示:

enum Prefixes {
    "ABC",
    "DEF",
    "GHI"
}

const hasPrefix = (str: string): boolean => Prefixes[str.substr(0, 3) as any] !== "undefined";

console.log(hasPrefix("123")); // false
console.log(hasPrefix("ABC")); // true
console.log(hasPrefix("DEF")); // true
console.log(hasPrefix("GHI")); // true
console.log(hasPrefix("GHII"));// true

const data = "ABC123";         // ABC123

console.log(hasPrefix(data));  // true
console.log(data);             // still ABC123

Here's 上述代码的 TypeScript 游乐场。


从您的问题来看,您似乎对检查前缀的动态方式感兴趣(... 字符暗示这一点(?))。这让我思考并想出了一个使用Set 数据类型的解决方案。考虑这个例子:

// Set data type ensures only uniques
type Prefix = string;
const prefixes: Set<Prefix> = new Set();

prefixes.add("ABC");
prefixes.add("ABC");
prefixes.add("DEF");
prefixes.add("GHI");

// No doubles here so we're good (note the double added ABC string)
console.log(prefixes);

// the typeguard
const hasPrefix = (str: any): str is Prefix => typeof str === "string" ? prefixes.has(str.substr(0, 3)): false;

console.log(hasPrefix(100));   // false
console.log(hasPrefix(0));     // false
console.log(hasPrefix(false)); // false
console.log(hasPrefix(true));  // false
console.log(hasPrefix(""));    // false
console.log(hasPrefix("123")); // false
console.log(hasPrefix("ABC")); // true
console.log(hasPrefix("DEF")); // true
console.log(hasPrefix("GHI")); // true
console.log(hasPrefix("GHII"));// true

const data = "ABC123";         // ABC123

if (hasPrefix(data)) {
    console.log(hasPrefix(data));  // true
    console.log(data);             // still ABC123
}

Here's 该代码的游乐场。

【讨论】:

  • 在你的第一个代码sn-p中,使用typeof Prefixes[str.substr(0, 3)] !== "undefined"would be more appropriate
  • @Nicolas 感谢您的反馈,我更新了第一个示例。
【解决方案2】:

我认为目前仅使用内置的 Typescript 类型是不可能的。 https://github.com/Microsoft/TypeScript/issues/6579 和参考提案:How to define a regex-matched string type in Typescript?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2017-05-18
    • 2021-09-02
    • 2018-11-03
    • 1970-01-01
    相关资源
    最近更新 更多