[英]TypeScript doesn't check return type when use generic
假設我們有以下代碼:
class Foo<T> {
lift<R>(): Foo<R> {
const bar = new Foo<T>()
return bar
}
}
為什么沒有錯誤? Foo<T>
和Foo<R>
可能是不同的類型。
TS 使用結構類型匹配而不是標稱。 這意味着如果它們的結構兼容,則兩種類型是兼容的。
您可以在此處閱讀有關泛型匹配如何發生的信息。
您的示例有效的原因是,從結構的角度來看,例如Foo<string>
或Foo<number>
之間沒有任何區別。 這將在 TS 中工作
const a: Foo<string> = new Foo<number>()
這也是您的函數有效的原因,因為Foo<TypeA>
與任何TypeA
和TypeB
的Foo<TypeB>
兼容。
如果您添加任何使用T
的其他內容,則結構兼容性會被破壞,並且您會收到預期的錯誤:
class Foo<T> {
field: T | null = null
lift<R>(): Foo<R> {
const bar = new Foo<T>()
return bar
}
}
Type 'Foo<T>' is not assignable to type 'Foo<R>'.
Type 'T' is not assignable to type 'R'.
'R' could be instantiated with an arbitrary type which could be unrelated to 'T'.(2322)
你可以在這里看到這個
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.