简体   繁体   中英

Typescript Javascript one line If…else…else if statement

I have this piece of code:

 if (service.isHostel) {
            return new Hostel({url: service.url});
        } else {
            return new booking({url: service.url});
        }

that I want to express in 1 line,

service.isHostel ? Hostel({url: service.url}) : return new booking({url: service.url})

but I have a compilation error:

Expression expected.

You need to add a new operator as well for Hostel and omit the return return statement inside of the ternary.

return service.isHostel ? new Hostel({url: service.url}) : new booking({url: service.url});

Another version is to choose different classes.

return new (service.isHostel ? Hostel : booking)({url: service.url});

You can only write expressions(piece of code which returns are value) inside ternary operation. return is a statement which can't be used inside the expression of ternary operators.

Here you have to return both the values you can use return before ternary

return service.isHostel ? new Hostel({url: service.url}) : new booking({url: service.url})

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