Skip to content

Check truthy/falsy-ness for non-primitives to identify unreachable code #44840

Open
@donaldpipowitch

Description

@donaldpipowitch

Suggestion

In some cases TypeScript can identify unreachable code and throws an error:

const isTrue = true;
if (isTrue === false) {
  console.log('Can never be reached.')
}

In other cases it is currently not possible, but it would be very helpful. (Maybe even with a suggestion what could have been meant - see array example.)

const isArray = ['hello'];
if (!isArray) {
  console.log('Can never be reached. You probably meant `if (!isArray.length) {`.')
}

const isObject = {};
if (!isObject) {
  console.log('Can never be reached.')
}

🔍 Search Terms

  • reachable / unreachable
  • dead code
  • condition
  • falsy / truthy
  • primitive / non-primitive
  • always

✅ Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code -> It can break code, but only to show potential bugs.
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Throw errors on unreachable code examples.

const isArray = ['hello'];
if (!isArray) { // error: This condition will always return false. Did you meant to check `isArray.length`?
  console.log('Can never be reached. You probably meant `if (!isArray.length) {`.')
}

const isObject = {};
if (!isObject) { // error: This condition will always return false.
  console.log('Can never be reached.')
}

// OR:
if (isArray) {
} else {
  console.log('Can never be reached. You probably meant `if (!isArray.length) {`.')
}

📃 Motivating Example

This week I saw a colleague which could have found a bug way sooner by introducing such a check. ❤️

💻 Use Cases

Finding bugs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureExperimentation NeededSomeone needs to try this out to see what happensSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions