Typescript: [Feature] Lift Assignment out of an if statement conitional

Created on 17 Dec 2017  ·  5Comments  ·  Source: microsoft/TypeScript

Inspiration: Kotlin

This code below

    if (age < 18) {
       message = "You are too young to vote"
    } else if (age === 100) {
        message = "Congratulations"
    } else {
        message = "You can vote"
    }

can be converted like this for productivity and brevity

    message = if (age < 18) {
        "You are too young to vote"
    } else if (age == 100) {
        "Congratulations"
    } else {
        "You can vote"
    }
Out of Scope Suggestion

Most helpful comment

All 5 comments

Also when (though it might not feel javascript-like like above mentioned)

   message = when {
        (age < 18) -> "You are too young to vote"
        (age == 100) -> "Congratulations"
        else -> "You can vote"
    }

You can do it:

message = age < 18 ?
        "You are too young to vote" :
    age == 100 ?
        "Congratulations" :
        "You can vote"

Typescript will not add new syntax if is not added to ecmascript first.

@RyanCavanaugh This looks cool and neat, the do expression
Sorry I am unfamiliar but what's the ES6 stage number that will let typescript have this do expression in the core?

@j-oliveras I know with ternary but as you might know that's not readable and I have whole JS community backed up with this 😄

I really feel do expressions are great! Thanks @RyanCavanaugh, Microsoft, Ecma & Rest :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

seanzer picture seanzer  ·  3Comments

Antony-Jones picture Antony-Jones  ·  3Comments

dlaberge picture dlaberge  ·  3Comments

MartynasZilinskas picture MartynasZilinskas  ·  3Comments

fwanicka picture fwanicka  ·  3Comments