简体   繁体   English

打字稿联合类型和接口

[英]Typescript Union Type and Interface

I am new in typescript, i don't understand why interface is not declare in object when i call an array or function property. 我是打字稿的新手,我不明白为什么当我调用数组或函数属性时,接口没有在对象中声明。 if i call it form any object then array or function property getting error. 如果我将其称为任何对象,则数组或函数属性会出错。

where i'm use address property as string then i declare interface in makeNewEmployee object then there are no error. 我在其中使用地址属性作为字符串,然后在makeNewEmployee对象中声明接口,然后没有错误。 i'm little bit confused about that. 我对此有些困惑。

here is my code 这是我的代码

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

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

here i'm use makeAnything interface in my makeNewEmployee object and declare address property as function , why i get error in console? 在这里,我在makeNewEmployee对象中使用makeAnything接口,并将address属性声明为function,为什么在控制台中出现错误?

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

You can use type guards to help the compiler know that address is a function. 您可以使用类型保护来帮助编译器知道address是一个函数。 See type guards . 请参阅防护罩

Examples: 例子:

// 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()); 
}

Or if you know for sure address is a function, you can cast it to any : 或者,如果您确定address是一个函数,则可以将其强制转换为any

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM