Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
854 views
in Technique[技术] by (71.8m points)

typescript - Make two types different by parameter

Consider next simplified example:

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

This type represents ref to object, typescripts thinks what this is string (this is correct). But how to make TS think it as two different strings? So next example will be incorrect:

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

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

But this is logically incorrect. Is it possible to create compile check for it in TS?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

type just introduces a type alias for another type. In your case both Ref<Blog> and Ref<User> 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 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 

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...