代码之家  ›  专栏  ›  技术社区  ›  daxim Fayland Lam

如何声明值约束类型?

  •  1
  • daxim Fayland Lam  · 技术社区  · 5 年前

    Ada

    type Year_type is range 1800 .. 2100;
    

    Raku

    subset Natural of Int where * ≥ 0;
    

    Kavorka

    Int $even where { $_ % 2 == 0 }
    

    TS公司

    type Natural = BigInteger /* hypothetical → */ where (n) => { return n >= 0 };
    
    2 回复  |  直到 5 年前
        1
  •  2
  •   jcalz    5 年前

    你不能,至少从TS3.8开始。

    有一个公开的建议, microsoft/TypeScript#15480 为了支持范围内的数字类型;如果您希望看到这种情况发生,您可能希望转到该问题,给它一个,如果您认为它特别有说服力,而且还没有被考虑进去,则可以描述您的用例。

    microsoft/TypeScript#26382 ,但我不知道这会不会真的发生。依赖类型很好,但我不知道它们是否会在语言中很快发生。

    在此之前,您可以做的最好的事情是创建一个类似于nominal的类型和一个用户定义的类型保护,以允许值是正确的类型。但所有这些都迫使开发人员在每次想要使用您的受限类型时执行一系列运行时测试,因为编译器无法强制或检查它:

    type EvenNumber = number & { ___isEven: true };
    
    function isEven(x: number): x is EvenNumber {
      return x % 2 == 0;
    }
    
    function divideByTwoEvenly(x: EvenNumber): number {
      return x / 2;
    }
    
    const a = divideByTwoEvenly(100); // error! 100 is not an EvenNumber
    const hundred = 100;
    if (isEven(hundred)) {
      const a = divideByTwoEvenly(hundred);
    } else {
      throw new Error("I'm SAD");
    }
    

    Playground link to code

        2
  •  1
  •   C.Champagne    5 年前

    据我所知,这里没有这样的约束或 Range 一个解决方案是创建一个实现这些约束的特定类。

    union types 可能有助于缩小范围:

    type EvenDigits  = 0 | 2 | 4 | 6 | 8;
    
    推荐文章