Make two types different by parameter

后端 未结 1 530
故里飘歌
故里飘歌 2020-12-11 22:41

Consider next simplified example:

type Ref = T[\'id\']

This type represents ref to object, typescripts thinks

1条回答
  •  生来不讨喜
    2020-12-11 23:08

    type just introduces a type alias for another type. In your case both Ref and Ref are really the same type string and thus they are fully compatible.

    You could use branded types, which use the way typescript determines type compatibility (structural compatibility) to make differently branded strings (or any type really) incompatible:

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

    You need to define helper functions to create instances of the types or use casting, but the types will be incompatible.

    This article has a bit more of a discussion on the topic. Also the typescript compiler uses this approach for paths

    0 讨论(0)
提交回复
热议问题