打字稿联盟类型和界面

时间:2017-05-16 15:10:33

标签: typescript interface

我是打字稿的新手, 当我调用数组或函数属性时,我不明白为什么接口没有在对象中声明。 如果我从任何对象调用它,那么数组或函数属性会出错。

其中我使用地址属性作为字符串然后我在makeNewEmployee对象中声明接口然后没有错误。 我对此有点困惑。

这是我的代码

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

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

这里我在makeNewEmployee对象中使用makeAnything接口并将地址属性声明为函数,为什么我在控制台中出错?

    ///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

1 个答案:

答案 0 :(得分: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());