Consider disallowing in
operator use with arbitrary key operands on closed types for which the keys are known
#59299
Labels
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
Suggestion
An idea for TypeScript
π Search Terms
in
operator, type guard, known property/props, closed type, rename propertyβ Viability Checklist
β Suggestion
The
in
operator serves as a type guard against record types: #10485As it is implemented, it allows checking for the presence of arbitrary keys on an object.
The suggestion would be to disallow using the
in
operator with key names that not one of the known keys in the object's type. This would prevent developer errors where the key for which the presence is checked is not one of the keys that was explicitly declared to the type system, and might for example contain a typo.This could be guarded behind a compiler option, so as to not introduce a breaking change.
Of course, the
in
operator has a wide range of uses, especially for type guarding property accesses on objects of completely unknown types, so these should be preserved:For cases where the original type of the variable was not permissive enough, but the programmer knows better, we can allow checking for the presence of the key with an explicit cast:
π Motivating Example
Currently, I can write a valid program to discriminate a union:
Now, let's say my British colleague has a pass at the code, renaming variable names to UK English:
the program remains valid, yet TypeScript is unable to provide any indication that the change had consequences.
With the proposed feature:
π» Use Cases
What do you want to use this for?
Preventing developer errors (typos), allowing for safe property renames.
What shortcomings exist with current approaches?
Does not warn of checks for presence of properties which are unknown to the type system (to allow for checking of properties not represented in the type system). This is especially evident when using the operator to discriminate a union, as the
in
operator key operand is always intended to be a known property in such cases.What workarounds are you using in the meantime?
https://stackoverflow.com/questions/70670913/type-safe-in-type-guard
The text was updated successfully, but these errors were encountered: