2017-05-16 106 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());