【问题标题】:Make two types different by parameter通过参数使两种类型不同
【发布时间】:2018-09-08 12:12:29
【问题描述】:

考虑下一个简化示例:

type Ref<T extends {id: string}> = T['id']

这个类型代表对象的引用,打字稿认为这是什么字符串(这是正确的)。 但是如何让 TS 认为它是两个不同的字符串呢? 所以下一个例子是不正确的:

let refBlog: Ref<Blog> = ...
let refUser: Ref<User> = ...

// TS allows this as both a strings:
refBlog = refUser

但这在逻辑上是不正确的。是否可以在 TS 中为其创建编译检查?

【问题讨论】:

    标签: typescript types


    【解决方案1】:

    type 只是为另一种类型引入了类型别名。在您的情况下,Ref&lt;Blog&gt;Ref&lt;User&gt; 实际上是同一类型 string,因此它们是完全兼容的。

    您可以使用品牌类型,它使用 typescript 确定类型兼容性(结构兼容性)的方式来使不同品牌的 strings(或任何类型)不兼容:

    class Blog {
        id: string  & { brand: 'blog' }
    }
    
    class User {
        id: string  & { brand: 'user' }
    }
    
    type Ref<T extends {id: string}> = T['id']
    
    function createUserId(id: string) : Ref<User> {
        return id as any
    }
    
    function createBlogId(id: string) : Ref<Blog> {
        return id as any
    }
    
    let refBlog: Ref<Blog> = createBlogId("1");
    let refUser: Ref<User> = createUserId("1");
    
    
    refBlog = refUser // error 
    

    您需要定义辅助函数来创建类型的实例或使用强制转换,但类型将不兼容。

    article 对此主题进行了更多讨论。打字稿编译器也将这种方法用于paths

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-02
      • 2022-06-16
      • 2020-09-18
      相关资源
      最近更新 更多