Narrowing for key type by `in` operator
reverofevil opened this issue ยท 9 comments
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];I was surprised that Typescript doesn't do this already
I guess this would also solve the issue of this code throwing an error.
for (const p in obj) {
delete obj[p];
}
Note that such narrowing is technically unsafe (although the current narrowing in #10485 is also technically unsafe for the same reason):
function f(v: { a: string }, k: string) {
if (k in v) {
// k is now "a" by #43284, so
v[k].toUpperCase();
}
}
const v = { a: "hello", b: 123 };
f(v, "b"); // kaboomThis 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 narrowing k, somewhat inconsistently:
declare const k: "bar";
declare const v: { foo: 0, baz: 1 };
if (k in v) {
// k is now never by 43284
// v is now {foo: 0, baz: 1, bar: unknown} by 50666
}Maybe there's some reasonable heuristic here? Like, if k is something wide like string then we want to narrow k and not v, but when k is narrow like a string literal we should... do something else?
@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.
interface A { a(): string };
interface B { b(): string };
function f(x: A | B): string {
if ("a" in x) {
return x.a(); // x.a is not a function
} else {
return x.b();
}
}
const x = { a: 10, b() { return "hello"; } };
const y: B = x;
f(y);Edit. Of course, you said exactly that, and I somehow missed it.
Note that such narrowing is technically unsafe (although the current narrowing in #10485 is also technically unsafe for the same reason)
Want to point out that this is even worse than that: Assuming that k in o narrowed k to keyof typeof o, what is the type of o[k] afterwards? There might be extra properties of who knows what type, and k might be one of them. In theory you could narrow k to an opaque keyof type (instead of a string union), but then the only safe type you could assign to o[k] is unknown...
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.
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.
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 errors
Current consensus is that this behavior would be wrong and so has a pretty high bar to justify changing it.
Is there anything preventing this be implemented for const asserted (readonly) object types?
This is wrong; just because you have a type originating in a const assertion doesn't mean the object is sealed.
const a = { x: 32 } as const;
const b = { x: 32, y: "hello" } as const;
const c: typeof a = b;
const s = Math.random() > 0.5 ? "x" : "y";
if (s in c) {
// Alleged: s is safely "x" here
// Reality: This branch is always hit, s could be "y"
}