-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Incorrect error on legitimate type overlap #41402
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
Comments
This is intentionally an error, but the wording needs work |
Hey @RyanCavanaugh Why would this be an error? It's simple, valid JS: function fn<T>(t: T) {
return t === '' // error
}
fn('') // but here we pass it |
I actually expected an explanation (why is this OK?) function fn<T extends unknown>(t: T) {
return t === '' // works
}
fn('') // works and works perfectly, but not the equivalent function fn<T>(t: T) {
return t === '' // fails
}
fn('') // works @RyanCavanaugh would you be so kind to explain, please :) |
A generic type parameter is comparable to the type of its constraint if a constraint was explicitly declared |
Should we build a library to replace our comparison operators, to make this simple use-case work? const equals = <A>(thing: unknown, other: A): thing is A => {
return thing === other;
};
function fn<T>(t: T) {
if (equals(t, '')) {
// t: T & string
} // works
}
fn(''); // works Why is the |
The same would apply without the additional type-guard:
Just of course the type information |
That's exactly what I'm complaining about.
I get that a generic I'm pointing out the fact that we could safely narrow But @RyanCavanaugh seems to say that it's not possible, and I would like to know why should we have such a limitation. Another example: function fn<A, B>(a: A, b: B) {
if (a === b) { // fails here
// ...
} else {
// ...
}
} const equals = <A>(thing: unknown, other: A): thing is A => {
return thing === other;
};
function fn<A, B>(a: A, b: B) {
if (equals(a, b)) { // works
// a: A & B
} else {
// a: A
}
} |
TypeScript Version: 4.1.0-dev-20201102
Search Terms:
This condition will always return 'false' since the types 'X' and 'Y' have no overlap.
Code
https://www.typescriptlang.org/play?jsx=0#code/GYVwdgxgLglg9mABMMAeAKgPgBRQFyLoCUiA3gFCJWIBOAplCDUlIgLweIDkXiA9H0R0aNODXIBfcuRTYeJAYgDuYgNYBnIA
Expected behavior:
It works when we extend
unknown
. While this works on simple generics, it becomes inconvenient when the type parameter is nested deeper in a type structure.https://www.typescriptlang.org/play?jsx=0#code/GYVwdgxgLglg9mABMMAeAKogpgDylsAEwGdFwBrMOAdzAD4AKKALkXQEpEBvAKEX8QAnLFBCCkURAF4ZiAORzEAeiWJqcQeWI8Avjx4oGCzirUatQA
Actual behavior:
Related issues
#27910
The text was updated successfully, but these errors were encountered: