Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Narrowing for key type by in operator #43284

Open
5 tasks done
reverofevil opened this issue Mar 17, 2021 · 9 comments
Open
5 tasks done

Narrowing for key type by in operator #43284

reverofevil opened this issue Mar 17, 2021 · 9 comments
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

Comments

@reverofevil
Copy link

reverofevil commented Mar 17, 2021

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];
@RyanCavanaugh RyanCavanaugh added 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 labels Mar 18, 2021
@Khufu-I
Copy link

Khufu-I commented Apr 15, 2021

I was surprised that Typescript doesn't do this already

@mhchem
Copy link

mhchem commented Apr 30, 2021

I guess this would also solve the issue of this code throwing an error.

for (const p in obj) {
    delete obj[p];
}

https://stackoverflow.com/q/67323880/8772169

@jcalz
Copy link
Contributor

jcalz commented May 16, 2021

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"); // kaboom

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 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?

Playground link

@reverofevil
Copy link
Author

reverofevil commented 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.

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);

Playground link

Edit. Of course, you said exactly that, and I somehow missed it.

@fatcerberus
Copy link

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...

@jcalz
Copy link
Contributor

jcalz commented 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
Copy link

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.

@DavFeng1
Copy link

DavFeng1 commented 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 errors

@RyanCavanaugh
Copy link
Member

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"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
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
Projects
None yet
Development

No branches or pull requests

8 participants