简体   繁体   中英

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. 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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