-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
can i rely on this weird yet handy behavior? if not what is a working alternative? #18074
Comments
I feel like I'm asking the obvious, but why not generic defaults? function fn<A, B, C, D, X = A | B | C | D>(one: X, another: X): void {
...
} |
because X defined as default generic const never: never = null as never;
function fn<A, B, C, D, X = A | B | C | D>(
one: X,
another: X,
test: (value: A | B | C | D) => void
): void {
test(one); // <-- bummer
} |
this ugliness works tho: const never: never = null as never;
function fn<A, B, C, D, X extends A | B | C | D = A | B | C | D>(
one: X,
another: X,
test: (value: A | B | C | D) => void
): void {
test(one);
} |
Maybe it works for your use case, but the generic-default-with-constraint still only declares Weird alias, works: function fn<A, B, C, D>(
a: A
test: (value: X) => void // <-- X usable here
X?: undefined // <-- this seems to pull X into visibility also
): void {
type X = A | B | C | D;
test(a); // works, A is assignable to X
} Generic with constraint, broken: function fn<A, B, C, D, X extends A | B | C | D = A | B | C | D>(
a: A,
test: (value: X) => void
): void {
test(a); // error! A is not assignable to X
} Note that in using the "weird but handy" method, I don't think you need to make the |
"use strict";
function f(y = (x = 1)) {
var x;
console.log(x, y)
}
f();
Note that currently we seem to have an emit bug on the above code as well. |
@jcalz you are right, damn, hacky way it is, @DanielRosenwasser it's not a bug but a useful feature, take off that bug label! ;) |
The above bug has been fixed |
i have a very complex generic function that depends on
A
,B
,C
,D
with a lot of parameters that involveA | B | C | D
one way or another , i want to save some time writingA | B | C | D
every time by aliasing ittype X = A | B | C | D
unfortunately there is no place for such alias within the function signature, however i discovered a hack that seems to make it work:i bet it's not how it was supposed to be working but this really saves me a ton of time in maintenance, please either:
same problem is with interfaces and there is no hack like with functions, so i have to write this:
The text was updated successfully, but these errors were encountered: