type JSONValue = string | {[x:string]:string}
function foo(p:JSONValue){
console.log(p.aaaa);
}
編譯器說:
型別“JSONValue”上不存在屬性“aaaa”。型別“字串”上不存在屬性“aaaa”.ts(2339)
但這會編譯:
type JSONValue = {[x:string]:string}
function foo(p:JSONValue){
console.log(p.aaaa);
}
為什么?怎么修?
uj5u.com熱心網友回復:
在觸發錯誤的行中,p已知是 a JSONValue,它可以是字串或具有[x:string]:string索引簽名的物件。如果它是一個字串,那么它確實沒有aaaa屬性。這基本上就是錯誤告訴你的內容。
例如,在下面的第一個console.log電話將不會產生,因為這兩個錯誤string,并{[x:string]:string}具有這樣的性質length。只有第二個日志呼叫會出現錯誤:
type JSONValue = string | { [x: string]: string }
function foo(p: JSONValue) {
console.log(p.length)
console.log(p.aaaa)
}
解決方案:型別縮小
顯然,您想aaaa從p 僅 IF p是 a訪問該屬性{[x:string]:string},而不是如果它是 a string,對嗎?所以把這個邏輯放在你的代碼中!像這樣:
function foo(p: JSONValue) {
if (typeof p === 'string') {
// Typescript knows p has type string within this block
} else {
// Typescript knows p is not a string, and thus
// by process of elimination must be a
// { [x: string]: string } within this block
console.log(p.aaaa)
}
}
或像這樣:
function foo(p: JSONValue) {
if (typeof p === 'object') {
console.log(p.aaaa)
}
}
uj5u.com熱心網友回復:
這里的問題是,當您進行控制臺日志記錄時,編譯器不知道 'p' 是字典還是字串。如果它知道它不是字串,那么它將正確編譯。這樣做的原因是因為字串沒有屬性“aaaa”。
你這樣做的方法是:
type JSONValue = string | {[x:string]:string}
function foo(p:JSONValue){
if (typeof p != "string") {
console.log(p.aaaa);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/405749.html
標籤:
下一篇:匯出具有不同名稱和型別的相同函式
