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