通过参数使两种类型不同 [英] Make two types different by parameter

查看:44
本文介绍了通过参数使两种类型不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下一个简化示例:

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

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

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

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

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

推荐答案

type 只是为另一种类型引入了一个类型别名.在您的情况下, RefRef 实际上是相同的类型 string,因此它们完全兼容.

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.

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

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

这篇关于通过参数使两种类型不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆