Sandro Rey
Sandro Rey

Reputation: 2999

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.

Upvotes: 0

Views: 11223

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386868

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

Upvotes: 2

Maheer Ali
Maheer Ali

Reputation: 36594

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})

Upvotes: 2

Related Questions