How should I rewrite the given snippet in order to make compiler fail?

Topics: General
Mar 26, 2014 at 3:28 PM
Consider:
function testA() : string {
    return Math.random() > 0.5 ? 1 : null;                              // a problem
}

function ifThenElse<r>(condition: boolean, thenResult: r, elseResult: r) : r {
    return condition ? thenResult : elseResult;
}

function testB() : string {
    return ifThenElse(Math.random() > 0.5, 1, null);                    // a problem
}

function lazyIfThenElse<r>(condition: boolean, toThenResult: () => r, toElseResult: () => r) : r {
    return condition ? toThenResult() : toElseResult();
}

function testC() : string {
    return lazyIfThenElse(Math.random() > 0.5, () => 1, () => null);    // expected a problem, but everything is fine!
}
The problem is that testC compiles as if everything was fine. Is there a way to get around this problem?
Mar 27, 2014 at 6:57 PM
There is some talk similar to this here: https://typescript.codeplex.com/discussions/397565
Coordinator
Mar 27, 2014 at 7:07 PM
The best thing to do would be to pass --noImplicitAny to the compiler. This would require you to write e.g. (): number => null in the third argument and prevent the 'any' type from leaking out.