Repository navigation
Closed
Labels
Design LimitationConstraints of the existing architecture prevent this from being fixedConstraints of the existing architecture prevent this from being fixed
Description
TypeScript Version: 2.8.1
Search Terms:
conditional type
Code
const a: TypeFromOption<"configurationA"> = {data: "test"}
const b: TypeFromOption<"configurationB"> = {data: 1}
interface Whatever<T> {
data: T
}
type Options = "configurationA" | "configurationB"
type TypeFromOption<T extends Options> =
T extends "configurationA" ? Whatever<string> :
T extends "configurationB" ? Whatever<number> :
never
const createThing = <T extends Options>(type: T): TypeFromOption<T> => {
switch (type) {
case "configurationA":
return a
case "configurationB":
return b
}
}Expected behavior:
I would expect that typescript should be able to infer that the return type of each case in the switch statement is consistent with what the conditional type returns for the given T
Actual behavior:
Type 'Whatever<string>' is not assignable to type 'TypeFromOption<T>'
Type 'Whatever<number>' is not assignable to type 'TypeFromOption<T>'
Adding as any after return a and return b causes it to work as expected and infer the correct return type for the function.
Related Issues:
Metadata
Metadata
Assignees
Labels
Design LimitationConstraints of the existing architecture prevent this from being fixedConstraints of the existing architecture prevent this from being fixed
Activity
RyanCavanaugh commentedon Apr 19, 2018
Union-constrained generics aren't narrowed, so we don't change the type of
typein theswitchand don't have any chance to even realize the return statements refer to different cases. I'm not sure there's any concrete next step we could do to fix this - in general we cannot reason very strongly about a type parameter because we can't reason about a domain that doesn't exist yet, though literal-union-constrained generics might be a special case. But there's no mechanism in place right now to unify the flow control behavior with the conditional types - without more scenarios I think this is pretty far out of scope.#23132 might be related
leighman commentedon Apr 20, 2018
Yeh, thought typescript might be able to do more because it was a union of literals.
Thanks for the info.
typescript-bot commentedon May 4, 2018
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.