[英]Generic constraints are ignored when inferring class parameters
當使用new
實例化通用 class時,會推斷其類型參數。 在這種情況下, 一般約束似乎被忽略了。
type MyType = { a?: number, b?: number };
class MyClass<T extends MyType = MyType> {
constructor(t: T) {}
method(t: T) {}
}
const myClass1 = new MyClass<MyType>({ a: 1 });
myClass1.method({ b: 1 });
const myClass2 = new MyClass({ a: 1 });
// Why is this error?
// T should extend `MyType` even though type was inferred from a constructor parameter.
myClass2.method({ b: 1 });
這是一個錯誤還是一個意圖? 可以防止泛型類的類型推斷嗎?
這是故意的。 泛型類型(在本例中為T
)的extends
子句僅指定對傳遞類型的約束。
類型{ a: number }
確實滿足約束,因為b
是可選的。
type T0 = { a: number } extends MyType ? true : false
// -> true
當它成功滿足約束時,類型{ a: number }
將成為類型T
(不繼承MyType
)。 由於b
不是{ a: number }
一部分,因此您會收到錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.