2017-10-07 142 views
0

具有與塊的問題 - 「類型‘未定義’不能被轉換爲類型‘T’」中的錯誤:類型「未定義」不能被轉換爲類型「T」

removeItem(key: string) { 
    this.map[key] = undefined as T ; } 

//代碼

class PrintMap <T> { 
private map : { [key: string] : T } = {}; 

setItem(key : string, item : T) { 
    this.map[key] = item; 
} 
getItem(key : string) { 
    return this.map[key]; 
} 
clear() { 
    this.map = {}; 
} 
    removeItem(key: string) { 
     this.map[key] = undefined as T ; 
    } 
print() { 
    for (let key in this.map) { 
     console.log(key , this.map[key]); 
    } 
} 

回答

0

Tundefined是不同的類型。

您應該簡單地使用delete this.map[key]刪除條目。

1

你可以簡單地將它轉換爲any這將繞過類型檢查:

this.map[key] = undefined as any; 
相關問題