Skip to content

No boolean coercion compiler option #14114

@brunnerh

Description

@brunnerh

One of the things that always bugged me about JS and tends to cause bugs of various sorts (just had another one last week) is the boolean coercion that happens in if clauses or when using boolean operators like || or ?:.

Here is an example:

var predicate = () => false;
if (predicate)
	alert("true branch");
else
	alert("false branch");

This will compile without issue and always end up executing the true branch, because the developer merely referenced the predicate function instead of calling it.

Another example (this time simply bad code):

function test(optionA: string, optionB: number)
{
	// Set defaults if none provided
	optionA = optionA || "[None]";
	optionB = optionB || 1;

	alert(`${optionA}, ${optionB}`);
}
test("", 0)

Empty string and zero get converted to false and the defaults get assigned even though possibly valid values were provided.

Having a compiler option that prevents implicit conversions like these would easily prevent some bugs. This changes nothing about the emitted code and would be an optional type safety measure like noImplicitAny, so i do not think there would be many implications to worry about.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions