Skip to content

A generic in a custom type guard is not considered for the return typeΒ #52051

Closed
@mckravchyk

Description

@mckravchyk

Bug Report

πŸ”Ž Search Terms

generic custom type guard

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type FooId  = `foo_${string}`
type BarId = `bar_${string}`
type FooBarId = FooId | BarId;

interface Foo {
    id: FooId
    type: 'foo'
}

interface Bar {
    id: BarId
    type: 'bar'
}

type FooBar = Foo | Bar;

function isFoo(id: FooBarId): id is FooId { }

function getFoo(id: FooId): Foo { }

function getBar(id: BarId): Bar { }

type FooBarFromId<T extends FooBarId> =
  T extends FooId ? Foo :
  T extends BarId ? Bar :
  FooBar;

function getFooBar<T extends FooBarId>(id: T): FooBarFromId<T> {
  // Type 'Foo' is not assignable to type 'FooBarFromId<T>'
  return isFoo(id) ? getFoo(id) : getBar(id);
}

// I'm using multiple declarations as a workaround

function getFooBar(id: FooId): Foo;
function getFooBar(id: BarId): Bar;
function getFooBar(id: FooBarId): FooBar;
function getFooBar(id: FooBarId): FooBar {
  return isFoo(id) ? getFoo(id) : getBar(id);
}

πŸ™ Actual behavior

I have a function that accepts a generic constrained argument and has a return type that depends on the generic. The return type of the implementation is not compatible with the return type in the definition.

πŸ™‚ Expected behavior

There should be no error in the return statement. FooBarFromId type and the return statement implementations are compatible, it's like the compiler is not considering the generic in the equation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions