代码之家  ›  专栏  ›  技术社区  ›  corgrath

是否可以在TypeScript中键入check String别名?

  •  2
  • corgrath  · 技术社区  · 7 年前

    给定此代码:

    type Firstname = string
    type Surname  = string
    
    const firstname: Firstname = "John";
    const surname:Surname = "Smith"
    
    function print(name: Firstname) {
        console.log(name)
    }
    
    /*
     * This should give a compile error
     */
    
    print(surname);
    

    有没有可能禁止通过 Surname 当函数需要 Firstname ?

    1 回复  |  直到 7 年前
        1
  •  6
  •   Titian Cernicova-Dragomir    7 年前

    你正在寻找所谓的品牌类型。在typescript中,类型兼容性是由结构决定的,因此别名不会使类型不兼容,但我们可以使用交集类型和唯一符号使它们在结构上不同:

    type Firstname = string & { readonly brand?: unique symbol }
    type Surname = string & { readonly brand?: unique symbol }
    
    const firstname: Firstname = "John"; // we can assign a string because brans is optional 
    const surname: Surname = "Smith"
    
    function print(name: Firstname) {
        console.log(name)
    }
    
    print(surname); // error unques symbol declarations are incompatible 
    

    这方面的不同变体可能有用,但基本思想是相同的,您可能会发现这些类似的答案有用: guid definition , index and position ,和 others

    推荐文章