【问题标题】:Typescript Union Type and InterfaceTypescript Union 类型和接口
【发布时间】:2017-05-16 15:10:32
【问题描述】:

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

我使用地址属性作为字符串然后我在 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

【问题讨论】:

    标签: typescript interface


    【解决方案1】:

    您可以使用类型保护来帮助编译器知道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());
    

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 2015-04-01
      • 2020-09-11
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多