Skip to content

Narrowing for key type by in operator #43284

Open
@reverofevil

Description

@reverofevil

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

added
Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this feature
SuggestionAn idea for TypeScript
on Mar 18, 2021
Khufu-I

Khufu-I commented on Apr 15, 2021

@Khufu-I

I was surprised that Typescript doesn't do this already

mhchem

mhchem commented on Apr 30, 2021

@mhchem

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

jcalz commented on May 16, 2021

@jcalz
Contributor

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

reverofevil commented on May 16, 2021

@reverofevil
Author

@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

fatcerberus commented on May 8, 2022

@fatcerberus

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

jcalz commented on Apr 19, 2023

@jcalz
Contributor

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

loucadufault commented on Sep 29, 2023

@loucadufault

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

fenghourun commented on Mar 14, 2024

@fenghourun

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

RyanCavanaugh commented on Mar 15, 2024

@RyanCavanaugh
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"
}
karlismelderis-mckinsey

karlismelderis-mckinsey commented on Sep 27, 2024

@karlismelderis-mckinsey

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

🤦
I expected TS to be more strict with readonly objects and require exact match

Should we then wait for truly only these keys and nothing else type? 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @jcalz@reverofevil@fatcerberus@RyanCavanaugh@Khufu-I

        Issue actions

          Narrowing for key type by `in` operator · Issue #43284 · microsoft/TypeScript