I am trying to understand how to use generic in typescript. I have the following code
foo<T extends X>(a:A,b:B): T{
// some logic
const c: C = doSomthing(a,b)
if (c!= null){
return {
a: A,
b: B,
c: C
} as Y; // Y extends X
} else {
return {
a: A,
b: B,
} as X;
}
}
However, it won't work: Y is assignable to the constraint of type T, but T could be instantiated with a different subtype of constraint How can I implement it right?
T extends X
means all types which have at least members a: A
and b: B
. Your function can't create objects satisfying every one of those types.
A correct typing for your function is X
. It isn't a generic function.
function foo(a:A,b:B): X {
// some logic
const c: C | null = doSomthing(a,b)
return c != null ? { a, b, c } as Y : { a, b };
}
You could also use the type X | Y
, which removes the need for the as Y
. X | Y
has the same values as X
, so is in some sense equivalent.
N.b. it is incorrect to specify the type of elements in an object literal, as { a: A }
is the syntax for associating the key a
with the value A
.