2017-05-16 156 views
0

我是新的打字稿, 我不明白爲什麼接口沒有在對象中聲明,當我調用數組或函數屬性。 如果我把它稱爲任何對象然後數組或函數屬性獲取錯誤。Typescript Union類型和接口

其中我使用地址屬性作爲字符串,然後我在makeNewEmployee對象中聲明接口,然後沒有錯誤。 我對此有點困惑。

這裏是我的代碼

interface makeAnything{ 
    user:string; 
    address:string| string[]| (()=>string); 
} 

/// address as string 
let makeNewEmployee:makeAnything = { 
    user:"Mirajehossain", 
    address:"Dhaka,Bangladesh" 
}; 
console.log(makeNewEmployee.address); 

在這裏我使用makeAnything接口在我makeNewEmployee對象和申報地址財產功能,爲什麼我在控制檯中看到錯誤?

///address as function 
let makeSingleEmployee:makeAnything = { 
    user:'Miraje hossain', 
    address:():any=>{ 
     return{ 
      addr:"road 4,house 3", 
      phone:18406277 
     } 
    } 
}; 
console.log(makeSingleEmployee.address()); ///getting error 

回答

0

您可以使用類型警衛來幫助編譯器知道address是一個函數。見type guards

例子:

// string or string[] cannot be instances of Function. So the compiler infers that `address` must be (()=>string) 
if (makeSingleEmployee.address instanceof Function) { 
    console.log(makeSingleEmployee.address());  
} 

// typeof makeSingleEmployee.address will be "function" when address is a function 
if (typeof makeSingleEmployee.address != "string" && typeof makeSingleEmployee.address != "object") { 
    console.log(makeSingleEmployee.address()); 
} 

或者,如果你肯定知道address是一個功能,您可以將其轉換爲any

console.log((makeSingleEmployee as any).address());