-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Suggestion: typeof arg
in conditional type uses typeof passed value, rather than declared type of parameter
#22984
Comments
function mapFooOrBar<T extends Foo | Bar, R>(
foobar: T,
mapFoo: T extends Foo ? ((value: Foo) => R) : ((impossible: never) => never),
mapBar: T extends Bar ? ((value: Bar) => R) : ((impossible: never) => never),
): R |
@mhegazy I understand what it is doing; my suggestion was that it not do that. Or that something that does not do that be added. I also addressed already why a generic parameter is not workable in this situation. What I need is a way to refer to exactly what See also the linked #21879 for why your suggestion doesn't work, and why making it work has already been rejected. Personally, I would have thought it would be better/more consistent to recognize |
not sure i understand what you mean.
|
#21879 does not work because of the generic parameter, and the possibility that the generic parameter does not precisely match the type of I am therefore looking for alternatives. Some way of referencing the actual type of |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
A workaround I attempted for #21879 was to use
typeof
on a function argument in a conditional type, to indicate which callback parameters were relevant. The code was this:With the idea being that if I call
mapFooOrBar(foo,
forfoo: Foo
, I should expect thatmapBar
will never be called, and thus never have a parameter and never have a return value.But the problem is that
typeof foobar extends Bar
is always true, becausetypeof foobar
evaluates toFoo | Bar
—its declared type. It would be better iftypeof
here used the type of the actual passed value, rather than the function parameter declaration type.Using a generic here does not work, because for example you could write
mapFooOrBar<Foo, {}>(foobar,
forfoobar: Foo & Bar
(nevermind thatFoo & Bar
is impossible for these definitions ofFoo
andBar
, TS allows it), allowing the user to claim noBar
will be passed while actually passing a value that is aBar
.For backwards compatibility/corner-cases, a new keyword might be better than
typeof
. I don't currently have a good suggestion for what that would be, though.The text was updated successfully, but these errors were encountered: