Skip to content

Narrowing types based on property accessΒ #46219

Closed
@trusktr

Description

@trusktr

Suggestion

πŸ” Search Terms

type narrowing based on property checks, similar to in operator.

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code. I don't think so, because errors are currently produced, but now there would be narrowing instead of errors.
  • 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

Lot's of JS code uses duck typing. For example:

πŸ“ƒ Motivating Example

class Foo {
    bar: object = {}
    meth() {}
}

declare const f: Foo | Foo[]

if (f.bar) { // Error, bar property does not exist on Foo | Foo[]
  f.meth()
}

playground

πŸ’» Use Cases

We can currently do something similar that actually works:

class Foo {
    bar: object = {}
    meth() {}
}

declare const f: Foo | Foo[]

if ('bar' in f) {
  f.meth()
}

playground

But using a property check would allow us to write code like we can (and like currently exists) in plain JS. The f.bar check would behave similar to the 'bar' in f check, and would narrow the type.

This would need to be limited to certain property types. For example, if Foo.bar were a number, then a value of 0 can make it result in a false even if the property exists. In this case TS would need to throw an error and would not be able to perform type narrowing in such cases.

If the type of Foo.bar is something that is always truthy (f.e. bar: Record<Foo, Bar> is always truthy) then type narrowing can be performed. The system would have to clearly report errors in cases when type narrowing can not be confidently performed based on the encountered type.

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