Repository navigation
Relate control flow to conditional types in return types #33912
Description
Search Terms
control flow conditional return type cannot assign extends
Suggestion
Developers are eager to use conditional types in functions, but this is unergonomic:
type Person = { name: string; address: string; };
type Website = { name: string; url: URL };
declare function isWebsite(w: any): w is Website;
declare function isPerson(p: any): p is Person;
function getAddress<T extends Person | Website>(obj: T): T extends Person ? string : URL {
if (isWebsite(obj)) {
// Error
return obj.url;
} else if (isPerson(obj)) {
// Another error
return obj.address;
}
throw new Error('oops');
}The errors here originate in the basic logic:
obj.urlis aURL, and aURLisn't aT extends Person ? string : URL
By some mechanism, this function should not have an error.
Dead Ends
The current logic is that all function return expressions must be assignable to the explicit return type annotation (if one exists), otherwise an error occurs.
A tempting idea is to change the logic to "Collect the return type (using control flow to generate conditional types) and compare that to the annotated return type". This would be a bad idea because the function implementation would effectively reappear in the return type:
function isValidPassword<T extends string>(s: T) {
if (s === "very_magic") {
return true;
}
return false;
}
// Generated .d.ts
function isValidPassword<T extends string>(s: T): T extends "very_magic" ? true : false;For more complex implementation bodies, you could imagine extremely large conditional types being generated. This would be Bad; in most cases functions don't intend to reveal large logic graphs to outside callers or guarantee that that is their implementation.
Proposal Sketch
The basic idea is to modify the contextual typing logic for return expressions:
type SomeConditionalType<T> = T extends string ? 1 : -1;
function fn<T>(arg: T): SomeConditionalType<T> {
if (typeof arg === "string") {
return 1;
} else {
return -1;
}
}Normally return 1; would evaluate 1's type to the simple literal type 1, which in turn is not assignable to SomeConditionalType<T>. Instead, in the presence of a conditional contextual type, TS should examine the control flow graph to find narrowings of T and see if it can determine which branch of the conditional type should be chosen (naturally this should occur recursively).
In this case, return 1 would produce the expression type T extends string ? 1 : never and return -1 would produce the expression type T extends string ? never : -1; these two types would both be assignable to the declared return type and the function would check successfully.
Challenges
Control flow analysis currently computes the type of an expression given some node in the graph. This process would be different: The type 1 does not have any clear relation to T. CFA would need to be capable of "looking for" Ts to determine which narrowings are in play that impact the check type of the conditional.
Limitations
Like other approaches from contextual typing, this would not work with certain indirections:
type SomeConditionalType<T> = T extends string ? 1 : -1;
function fn<T>(arg: T): SomeConditionalType<T> {
let n: -1 | 1;
if (typeof arg === "string") {
n = 1;
} else {
n = -1;
}
// Not able to detect this as a correct return
return n;
}Open question: Maybe this isn't specific to return expressions? Perhaps this logic should be in play for all contextual typing, not just return statements:
type SomeConditionalType<T> = T extends string ? 1 : -1;
function fn<T>(arg: T): SomeConditionalType<T> {
// Seems to be analyzable the same way...
let n: SomeConditionalType<T>;
if (typeof arg === "string") {
n = 1;
} else {
n = -1;
}
return n;
}Fallbacks
The proposed behavior would have the benefit that TS would be able to detect "flipped branch" scenarios where the developer accidently inverted the conditional (returning a when they should have returned b and vice versa).
That said, if we can't make this work, it's tempting to just change assignability rules specifically for return to allow returns that correspond to either side of the conditional - the status quo of requiring very unsafe casts everywhere is not great. We'd miss the directionality detection but that'd be a step up from having totally unsound casts on all branches.
Use Cases / Examples
TODO: Many issues have been filed on this already; link them
Workarounds
// Write-once helper
function conditionalProducingIf<LeftIn, RightIn, LeftOut, RightOut, Arg extends LeftIn | RightIn>(
arg: Arg,
cond: (arg: LeftIn | RightIn) => arg is LeftIn,
produceLeftOut: (arg: LeftIn) => LeftOut,
produceRightOut: (arg: RightIn) => RightOut):
Arg extends LeftIn ? LeftOut : RightOut
{
type OK = Arg extends LeftIn ? LeftOut : RightOut;
if (cond(arg)) {
return produceLeftOut(arg) as OK;
} else {
return produceRightOut(arg as RightIn) as OK;
}
}
// Write-once helper
function isString(arg: any): arg is string {
return typeof arg === "string";
}
// Inferred type
// fn: (arg: T) => T extends string ? 1 : -1
function fn<T>(arg: T) {
return conditionalProducingIf(arg, isString,
() => 1 as const,
() => -1 as const);
}
let k = fn(""); // 1
let j = fn(false); // -1Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- All of these are errors at the moment
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Activity
jack-williams commentedon Oct 9, 2019
FWIW: this is exactly the same problem faced here in #33014.
Can users not just use an overload to emulate this today?
Is it possible to cleanly handle the following, without rebuilding the CFG on demand in the checker?
jcalz commentedon Oct 10, 2019
If generic type parameters could be narrowed via control flow analysis then perhaps this would also address #13995?
jack-williams commentedon Oct 10, 2019
I don't think this is really a solution to type parameter narrowing in general. There are ways that this could be unsound because of the previously discussed points where a type guard doesn't provide sufficient information to narrow a type-variable. Two examples:
I think the solution is relying on two points: the conditional type is distributive, and the constraint of the check type is 'filterable' with respect to the extends type in each conditional type. That is:
Given a type parameter
T extends C, and a conditional typeT extends U ? A : B, then for all typesV:Vis assignable toC, andUandVare not disjointVthat is assignable toU.jcalz commentedon Nov 12, 2019
Cross-linking to #22735, the design limitation addressed by this suggestion
Birowsky commentedon Jan 6, 2020
Just an SO question as another reference.
dgreensp commentedon Jan 9, 2020
As proposed, I think this goes too far in the direction of unsoundness. Knowing that a value
argof typeTis a string doesn't tell you thatT extends string, it actually tells you thatTis a supertype of string! This proposal would basically have the compiler analyze your code to see if it might be doing something correct, and then remove errors and the need for casts, which yes does achieve backwards compatibility and reduced errors and casts, but at a high cost in being able to trust the compiler's judgment.I think a good starting point would be an example function that is self-consistent in terms of the relationship between its argument types and return type. If
fn<string>("x")returns1andfn<unknown>("x")returns-1at the type level, something is already wrong, because a function can't return 1 and -1 for the same input value.How about something like:
Here each conditional specializes the output for a specialized input, like a type-safe overload. Analysis should proceed starting from the return type. If
T extends number, does the function return 'N'? If the compiler can prove that, bingo.RyanCavanaugh commentedon Jan 9, 2020
David Greenspan (@dgreensp) I don't believe the proposal in the OP introduces any novel unsoundness, specifically because the logic is only applied to
returnexpressions which are strictly a covariant position. Can you show an example?jack-williams commentedon Jan 9, 2020
I think my examples here show unsound calls.
dgreensp commentedon Jan 9, 2020
Ryan Cavanaugh (@RyanCavanaugh) In your example:
Substituting
unknownforT:Or substituting
string | numberforT:So I think the compiler should not allow the example. It would be great to design this feature so that all valid substitutions for T produce valid typings, first, and only be more lenient if that proves too limiting. Fundamentally, all the compiler can prove at the site of
return 1is thatargis aTandargis a string. It does not follow thatTextends string, so there's no single branch of the conditional that applies to this return statement. (The else branch that returns -1 is a different story, as described below, because ifTdoes extend string, then it is unreachable.)In my example, the same substitutions are correct, for example substituting
unknownfor T:A safe alternative proposal would be... I think, first allow returning a value that's assignable to all the branches of the conditional return value (or the intersection of the branches). So in a function whose return value is
A extends B ? C : D, you can always return a value of typeC & D. Then omitCat those return sites that are unreachable ifAis replaced byB.In other words, the contextual return type is
Din places that are unreachable ifAis narrowed toB, andC & Dotherwise.So in the original example:
Code that is crafted to be "correct," like my example, will work, as follows:
dgreensp commentedon Jan 10, 2020
simonbuchan commentedon Apr 9, 2020
Overloads work for the original example:
What are they doing different?
arobinson commentedon Oct 16, 2020
Here is another use case where it seems to be the same issue:
https://stackblitz.com/edit/rxjs-wdvejf?file=index.ts
Here a conditional type bound to a method argument and return value are unable to handle the valid cast
nxpatterns commentedon Apr 4, 2021
My workaround (in a simpler example from the official documentation) is explicitly casting to the expected type. Even if it is not an elegant solution and requires an intermediate step with
<unknown>, the compiler remains silent:type IdLabel = { id: number }; type NameLabel = { name: string }; type NameOrIdType<T extends number | string> = T extends number ? IdLabel : NameLabel; function createLabel<T extends number | string>( paramNameOrId: T, ): NameOrIdType<T> { if (typeof paramNameOrId === 'string') { - return { name: paramNameOrId }; + return <NameOrIdType<T>>(<unknown>{ name: paramNameOrId }); } else { - return { id: paramNameOrId }; + return <NameOrIdType<T>>(<unknown>{ id: paramNameOrId }); } } let a = createLabel('typescript'); // { name: 'typescript' } let b = createLabel(4.1); // { id: 4.1 }22 remaining items
ehaynes99 commentedon Feb 3, 2023
Correct you are, but that case already works. :-D
ehaynes99 commentedon Feb 3, 2023
There are no "external types", only types that are in scope:
I completely agree that all of the different cases you're bringing up are different cases. :-) All conditional return types are overloads, but not all overloads have conditional return types. You're bringing up a lot of the second case, and those aren't related to this issue.
You opened an issue about overloads, cited my comment as support for it, and then came here to say that it's not the same case as overloads. For the record, I don't care at all about the semantics of the existing overload syntax. It's an anti-feature like
enumthat I could dispense with entirely if we had a solution that allowed a type definition for overloads independent of implementation. const assertions allows deprecation ofenum, and this would allow deprecation of the current version of overloads.You've said "easy to implement" a dozen times or so. When people who actively maintain the compiler on a daily basis are telling you otherwise, you're going to need to produce the PR for anyone to believe you.
I don't want to pollute this thread anymore. If you disagree, you can post it in this gist, but you really need to enumerate your cases, because pointing out that there are a lot of different cases without listing them is a poor preface to calling something easy.
margaretdax commentedon Nov 21, 2023
Hey Gabriela Araujo Britto (@gabritto) any update on this? Honestly one of my biggest pains working w/ TypeScript has been these sorts of weird edge cases in the type system. Also, for this example in the docs, it is still not possible to write an implementation that does not require type assertions.
gabritto commentedon Nov 21, 2023
Margaret Dax (@margaretdax) I am slowly working on it. I'm close to having a working prototype, but it's been tricky to make it work in a mostly sound way.
Meanwhile, real world examples of where you'd want to use this feature are more than welcome.
timotheeandres commentedon Dec 6, 2023
Hello! I think I have a relevant example here:
https://stackoverflow.com/questions/77612251/typescript-conditional-type-depending-on-whether-type-is-undefined
gabritto commentedon Dec 6, 2023
Thanks for the example, it has a couple things that don't currently work with my in-progress prototype, but that I hope I can make work.
ehaynes99 commentedon Dec 7, 2023
Here's another, similar to something I recently did around RabbitMQ. Depending on the type of the exchange, I want the signature of a publish function to be different (Rabbit just being an example, so mocking it here):
Playground Link:
The problem is further compounded if you want varying numbers of generic parameters. RabbitMQ has a "topic exchange" that uses structured strings as keys, so it would be nice to be able to strongly type those. The compiler loses all ability to infer input or output types at that point.
Playground Link:
That case probably makes this more difficult, but it is covered with standard overloading. This is perfectly valid:
mtinner commentedon Jul 11, 2024
Another overloading without usage of
anyor type assertion:jakebailey commentedon Feb 28, 2025
Reopening this, since it was reverted in #61136 (but planned for 5.9).
docs: add Library Typing Best Practices to CLAUDE.md
feat(lite): add service() for context-aware method containers (#178)
Wire a voice-fidelity critic into check:all; fix 2 silent-letter clips