Repository navigation
Narrowing for key type by in operatorΒ #43284
Description
Suggestion
A k in v check should narrow type of k: K to K & keyof typeof v.
π Search Terms
in operator narrowing
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- 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
This code should compile due to narrowing on x:
const o = {foo: 1, bar: 2} as const;
const x: string = 'foo';
if (x in o) {
const y: "foo" | "bar" = x; // OK
}Currently it could be made with custom type guard
const in_ = <K extends string, O>(key: K, object: O): key is K & keyof O => key in object;
if (in_(x, o)) {
const y: "foo" | "bar" = x; // OK
}π Motivating Example
When validating a JSON with some kind of AST (or otherwise containing a tagged union) the only type we can have for a tag is a string.
const validateDisjointUnion = <O extends object>(
nodeTypeValidators: { [K in keyof O]: (value: O[K]) => boolean },
value: Json,
) => {
if (typeof value !== 'object' || !('type' in value)) throw 42;
const {type} = value;
if (typeof type !== 'string' || !(type in nodeTypeValidators)) throw 42;
// expression of type 'string' can't be used to index type '{ [K in keyof O]: (value: O[K]) => boolean; }'.
return nodeTypeValidators[type](value);
}π» Use Cases
in_ solves the issue, but it involves a type guard. Type guards are "dangerous" in a sense that they can be used improperly (for example, !(key in object) would compile as well, but would lead to runtime error).
There is a related feature request to narrow type for second parameter of in operator. As far as I'm aware, there is no syntax to specify type of in_ that would guard on both parameters at the same time.
const guardBoth = <A, B>(a: A, b: B): (a is string) & (b is string) => { ... };Edit. Not even
// A type predicate cannot reference a rest parameter.(1229)
const in_ = <K extends string, O, T>(...args: [K, O]): args is [K & keyof O, O & { [L in K]: unknown }] => args[0] in args[1];
Activity
Khufu-I commentedon Apr 15, 2021
I was surprised that Typescript doesn't do this already
mhchem commentedon Apr 30, 2021
I guess this would also solve the issue of this code throwing an error.
https://stackoverflow.com/q/67323880/8772169
jcalz commentedon May 16, 2021
Note that such narrowing is technically unsafe (although the current narrowing in #10485 is also technically unsafe for the same reason):
This is maybe fine, but people should be aware of it.
Also, the suggestion in #21732 (edit: implemented by #50666) and this suggestion acting in concert could do weird things, since on the one hand we'd be extending
vto add a new known property, and on the other hand we'd be narrowingk, somewhat inconsistently:Maybe there's some reasonable heuristic here? Like, if
kis something wide likestringthen we want to narrowkand notv, but whenkis narrow like a string literal we should... do something else?Playground link
reverofevil commentedon May 16, 2021
Joe Calzaretta (@jcalz) Yes, of course, but to make it correct TS would need to distinguish closed and open object types, like Flow did. Right now
inworks incorrectly even without any changes to type system.Playground link
Edit. Of course, you said exactly that, and I somehow missed it.
fatcerberus commentedon May 8, 2022
Want to point out that this is even worse than that: Assuming that
k in onarrowedktokeyof typeof o, what is the type ofo[k]afterwards? There might be extra properties of who knows what type, andkmight be one of them. In theory you could narrowkto an opaque keyof type (instead of a string union), but then the only safe type you could assign too[k]isunknown...jcalz commentedon Apr 19, 2023
Seeing how #48149 was declined, should this one be declined as well? Or should the other be undeclined but a duplicate of this? Just trying to understand where this feature request stands.
loucadufault commentedon Sep 29, 2023
Is there anything preventing this be implemented for
constasserted (readonly) object types? The pitfalls mentioned above shouldn't apply since the object type is known exactly.fenghourun commentedon Mar 14, 2024
hello what's the consensus on this? typescript currently suggests we use type-guards in these situations which to me feels no better than type casting
... as Fooand can still result in runtime errorsRyanCavanaugh commentedon Mar 15, 2024
Current consensus is that this behavior would be wrong and so has a pretty high bar to justify changing it.
This is wrong; just because you have a type originating in a
constassertion doesn't mean the object is sealed.karlismelderis-mckinsey commentedon Sep 27, 2024
π€¦
I expected TS to be more strict with
readonlyobjects and require exact matchShould we then wait for
truly only these keys and nothing elsetype? π€AceCodePt commentedon Jan 9, 2026
Shouldn't there be a definition of exact match? Why don't we have the const the exact match?
Narrow key variable type in `in` expressions for literal unions
Narrow key variable type in `in` expressions for literal unions