2016-11-22 58 views
2

Condidering這個例子打字稿工會接口和原始

interface fooInterface { 
    bar: any; 
} 
function(value: fooInterface | string) { 
    value.bar 
} 

的錯誤是:住宅「酒吧」上不存在類型「(fooInterface |字符串)」

我做錯了明顯。我想說的基本上是:value是一個實現fooInterface或字符串的對象。

我該怎麼做?

謝謝

+0

是的工會類型是正確的說法。但是,如果它是一個字符串,它不會有'bar'屬性,所以這樣訪問它是一個錯誤。你究竟在做什麼? – artem

+0

如果您確信該值包含fooInterface值,則可以通過'( value).bar'或'(value as fooInterface).bar'來說明TypeScript的真相。 – Misaz

回答

2

不能使用value.bar,因爲它不是絕對安全。它可能是安全的(因爲值可能是一個字符串),但編譯器並不知道這一點,除非它確定,否則它不會讓你做.bar。你可能想要做的是使用type guard

if (typeof value !== "string) { 
    value.bar 
    // This compiles happily, because inside this if, value has 
    // type 'fooInterface'. That's because TS now knows it isn't a string, 
    // so *must* be a fooInterface. 
} 

你可以玩這個in the typescript playground:請注意,只有「之一value.bar小號失敗,因爲它知道,只有一個是錯誤的。

如果你不能/不想這樣做,你可以通過類型斷言告訴編譯器你知道你在做什麼(例如var definitelyFoo = (fooInterface) value),但是一個守護者通常是更好的選擇。

+0

有道理,它強制我的代碼更健壯,謝謝。 –

0

如果,你是在告訴value要麼fooInterface型或string的,你必須檢查的類型,然後才能與value工作。在你的情況下,你只需使用typeof檢查value是否爲string。如果不是,則爲fooInterface

interface fooInterface { 
    bar: any; 
} 
function(value: fooInterface | string) { 
    if (typeof value === "string") { 
     // The compiler now knows that value is string 
    } 
    else { 
     /* The compiler is smart and knows that the value 
      must be of type fooInterface. */ 

     value.bar 
    } 
} 

在其他情況下,你將不得不使用instanceof(用於檢查對象是否爲特定typeof運算類)或您own type checks(如果有多個接口或自定義類型)。