How to indicate that a path is not available in TypeScipt

I have Typescript code that looks essentially like this

if( ... ) 
   result  = $(document.createElement("div")) ;
} else if( ... ) {
    result  = $(document.createElement("div")) ;
} else {
    assert.unreachable( "Unknown label in buildHTML.") ;
}
result.attr( "data-childNumber", childNumber.toString() ) ; 

The return type assert.unreachableis equal never.

The last line displays the error message "Variable Result" is used before the assignment.

It seems to me that the result neverfrom assert.unreachableshould tell the compiler that there is no way from the part else.

I know that I can suppress the error by adding throw null;to the end else, but it seems inelegant.

A similar problem arises in the definition unreachable. It looked like this:

export function unreachable( message? : string ) : never {
    if( message===undefined ) message = "Unreachable code reached." ;
    else message = "Unreachable code reached: "+message ;
    raiseTheAlarm( message ) ;
}

where the result of the result raiseTheAlarmis equal never. In this case, I got the error "A function returning" never "cannot have an reachability endpoint."

, return raiseTheAlarm. . (, throw null; , .)

, ?

+4
2

, assert.unreachable , else.

. , - , never , , . , , .

, - , , . - never . , , never , .

if( ... ) 
   result  = $(document.createElement("div")) ;
} else if( ... ) {
    result  = $(document.createElement("div")) ;
} else {
    result = assert.unreachable( "Unknown label in buildHTML.") ;
}
result.attr( "data-childNumber", childNumber.toString() ) ; 

unreachable - ​​

return raiseTheAlarm( message ) ;

.

+1

()

else {
    return assert.unreachable( "Unknown label in buildHTML.") ;
}

(b) ( @artem)

else {
    result = assert.unreachable( "Unknown label in buildHTML.") ;
}

()

else {
    assert.unreachable( "Unknown label in buildHTML.") ;
    throw null ;
}

().

+1

Source: https://habr.com/ru/post/1678913/


All Articles