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 codeThis wouldn't change the runtime behavior of existing JavaScript codeThis could be implemented without emitting different JS based on the types of the expressionsThis 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
v
to 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
k
is something wide likestring
then we want to narrowk
and notv
, but whenk
is narrow like a string literal we should... do something else?Playground link
reverofevil commentedon May 16, 2021
@jcalz Yes, of course, but to make it correct TS would need to distinguish closed and open object types, like Flow did. Right now
in
works incorrectly even without any changes to type system.Playground link
Edit. Of course, you said exactly that, and I somehow missed it.
keyIn
sindresorhus/ts-extras#47objectHas
sindresorhus/ts-extras#48fatcerberus commentedon May 8, 2022
Want to point out that this is even worse than that: Assuming that
k in o
narrowedk
tokeyof typeof o
, what is the type ofo[k]
afterwards? There might be extra properties of who knows what type, andk
might be one of them. In theory you could narrowk
to an opaque keyof type (instead of a string union), but then the only safe type you could assign too[k]
isunknown
...in
operator #50666jcalz 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.
in
operator narrowing (key in obj
) doesn't work properly when key type is a string union #55561loucadufault commentedon Sep 29, 2023
Is there anything preventing this be implemented for
const
asserted (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 Foo
and 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
const
assertion doesn't mean the object is sealed.karlismelderis-mckinsey commentedon Sep 27, 2024
🤦
I expected TS to be more strict with
readonly
objects and require exact matchShould we then wait for
truly only these keys and nothing else
type? 🤔