我有一個通用類ImmutableGeneric<T>和這個類的一些實體。
我想創建一個Map其中每個鍵都是 的實體ImmutableGeneric,并且型別的鍵ImmutableGeneric<T>必須與型別的值相關聯T。
class ImmutableGeneric<T>{
constructor(
public readonly value: T
){}
}
const NUMBER = new ImmutableGeneric(1)
const STRING = new ImmutableGeneric('hi')
const map = new Map<ImmutableGeneric<???>,???>()
// Ok
map.set(NUMBER, 5)
map.set(STRING, 'hello')
// Wrong, there should be a warning here
map.set(NUMBER, 'clearly not a number')
這可能嗎?
uj5u.com熱心網友回復:
目前沒有辦法將兩者聯系起來,但您可以擴展Map:
class ImmutableGenericMap extends Map<ImmutableGeneric<unknown>, unknown> {
set<T>(key: ImmutableGeneric<T>, value: T) {
return super.set(key, value);
}
}
操場
您也可以對其他方法(get、has、delete、entry、forEach)做同樣的事情。
不幸的是,即使介面合并也無法解決此問題,因為如果您嘗試添加多載來解決此問題,則只會使用第一個(原始)多載。您最終將不得不自己傳遞多載的泛型......這根本不是 DRY,所以我只會繼續擴展Map.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511219.html
標籤:打字稿字典仿制药
