Typescript泛型类型检查无法按预期工作 [英] Typescript generic type check not working as expected

查看:57
本文介绍了Typescript泛型类型检查无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个简单的测试夹具:

export interface ITest1 {}
export interface ITest2 {}
export interface ITestGeneric<T> {}

export function test() {
  let p: ITestGeneric<ITest1> = {}
  let q: ITestGeneric<ITest2> = p;
}

我希望最后一行失败,因为在C#中,这种不兼容的类型分配不起作用.但是,打字稿对此进行了编译,而没有任何抱怨.

有人可以告诉我为什么会这样,以及我必须做些什么才能使它失败?

解决方案

这是因为打字稿使用结构兼容性来确定两种类型是否兼容.在您的情况下,由于ITestGeneric没有成员,因此它基本上与任何东西兼容.如果您开始添加属性,则不兼容性将很快出现:

export interface ITest1 { t1: string}
export interface ITest2 { t2: number}
export interface ITestGeneric<T> { value: T}

export function test() {
    let p: ITestGeneric<ITest1> = {} // error
    let q: ITestGeneric<ITest2> = p; // error
}

您可以在此处 中了解有关类型兼容性的更多信息. >

I have made a simple test fixture:

export interface ITest1 {}
export interface ITest2 {}
export interface ITestGeneric<T> {}

export function test() {
  let p: ITestGeneric<ITest1> = {}
  let q: ITestGeneric<ITest2> = p;
}

I would expect the last line to fail, because in C# such incompatible type assignments don't work. However, typescript compiles this without complaint.

Can someone tell me why this works and what I have to do to make this fail?

解决方案

This is because typescript uses structural compatibility to determine if two types are compatible. In your case since ITestGeneric has no members, it is basically compatible with anything. If you start adding properties, incompatibilities will quickly appear:

export interface ITest1 { t1: string}
export interface ITest2 { t2: number}
export interface ITestGeneric<T> { value: T}

export function test() {
    let p: ITestGeneric<ITest1> = {} // error
    let q: ITestGeneric<ITest2> = p; // error
}

You can read more about type compatibility in typescript here

这篇关于Typescript泛型类型检查无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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