I'm currently attempting to utilize conditional types with generics in order to determine another type, but I am facing issues with the narrowing of the conditional type. Specifically, I am looking to narrow down the conditional type based on the parameter's type.
export function foo<T extends "a" | "b">(parameter: T) {
type Foo = T extends "a" ? 1 : 2;
let foo: Foo;
if (parameter === "a") foo = 1;
else foo = 2;
}
I believe this issue is similar to the one discussed in Conditional type is not being narrowed by if/else..., although I am unsure of the exact cause.
Are there any best practices for situations like these where I need to determine a type based on the parameter's type?
P.S. I prefer not to use Discriminated Unions as it would require adding parameters like seen below.
type A = { type: "a"; foo?: 1 };
type B = { type: "b"; foo?: 2 };
export function foo<T extends A | B>(parameter: T) {
// The parameter is not strict. (foo can be one of parameter)
if (parameter.type === "a") parameter.foo = 1;
else parameter.foo = 2;
}
The above details outline my final attempt at solving this issue. I have searched through various resources, but have yet to find an explanation regarding this specific problem.