Skip to content

Nullable nested properties breaks inference for type guardsΒ #60244

Closed as not planned
@leonaves

Description

@leonaves

πŸ”Ž Search Terms

nullable items nested typeguard type guards

πŸ•— Version & Regression Information

  • This changed between versions 0 and 5.6.3

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.7.0-dev.20241016#code/ATAuE8AcFNgMQPYIEIEMBOwC8wDeAoEEAIwwC5gBnUdASwDsBzYAH2HoFcAbLgbkOABffgIgxgAOW5dUxLtACSoaAFtseASABmSCohQZW7afxDD8oqLAkJQUnrPlLV6gkWA6EepGnSmhIiAAxgj01MC0yioAEqiU+uoAFJGqFPYycopRAJQUKWq0lJK26Y5ZLlgAfBru6NCgHOj0EVEAdJ7AAIRYOJw8-uYCIWGgLapFOADamjXuHrqzc8Ck6BQA5AAW0DwIawA0M2YH7oLHRLjzXsY8QmcAuoHAw+FcCIwAgujoqOAA8lrOFQTYCJLQcehBQGUNIlaRlQGTO7ZbDVNxEZ4IeStV6MUHgyFRSjZAaPZ6jLS0LjKOoAEyh6nylHalOpySisXiSGJAhxn2+fwBhNBLOgtKhxKAA

πŸ’» Code

  type FooBar = {
    bar: string | null;
  };

  type NullableItem = {
    foo: FooBar | null;
  };

  type NotNullableItem = {
    foo: FooBar;
  };

  const itemHasFoo = (item: NullableItem): item is NotNullableItem => {
    return item.foo !== null;
  };

  const items = [
    {
      foo: {
        bar: 'hello',
      },
    },
    { foo: null },
  ];

  const logArrayOfItems = (funcItems: NotNullableItem[]) => {
    console.log(funcItems);
  };

  const filteredItems = items.filter(itemHasFoo);
  logArrayOfItems(filteredItems);

πŸ™ Actual behavior

Type guard itemHasFoo does not narrow type to NotNullableItem, but when FooBar is changed to:

  type FooBar = {
    bar: string;
  };

It works fine, something about the nullable property of FooBar seems to stop the inference of that type correctly.

πŸ™‚ Expected behavior

I expect the typeguard to correctly narrow the type to NotNullableItem and therefore not error.

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions