Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 通过参数使两种类型不同_Typescript_Types - Fatal编程技术网

Typescript 通过参数使两种类型不同

Typescript 通过参数使两种类型不同,typescript,types,Typescript,Types,考虑下一个简化示例: type Ref<T extends {id: string}> = T['id'] type Ref=T['id'] 此类型表示对对象的引用,typescripts认为这是字符串(这是正确的)。 但如何让TS将其视为两个不同的字符串? 所以下一个例子是不正确的: let refBlog: Ref<Blog> = ... let refUser: Ref<User> = ... // TS allows this as both a

考虑下一个简化示例:

type Ref<T extends {id: string}> = T['id']
type Ref=T['id']
此类型表示对对象的引用,typescripts认为这是字符串(这是正确的)。 但如何让TS将其视为两个不同的字符串? 所以下一个例子是不正确的:

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

// TS allows this as both a strings:
refBlog = refUser
让refBlog:Ref=。。。
让加油机:Ref=。。。
//TS允许将其作为两个字符串:
refBlog=加油机

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

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

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

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 
class博客{
id:string&{brand:'blog'}
}
类用户{
id:string&{brand:'user'}
}
类型Ref=T['id']
函数createUserId(id:string):Ref{
返回任意id
}
函数createBlogId(id:string):Ref{
返回任意id
}
让refBlog:Ref=createBlogId(“1”);
let refuer:Ref=createUserId(“1”);
refBlog=加油机//错误
您需要定义辅助函数来创建类型的实例或使用强制转换,但类型将不兼容

这是一个关于这个话题的讨论。typescript编译器也使用这种方法