-
Notifications
You must be signed in to change notification settings - Fork 12.7k
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
Union type doesn't match the description in the Handbook #51062
Comments
Duplicate of #20863. The expected behavior is the actual behavior. Your value is both edit: again 30 seconds too late, what's going on?! |
The explanation makes sense. Although it is not clear from the error that it is "regular" error or "linter" error. type A = { a: number };
type B = { b: string };
function isA(value: A | B): value is A {
return "a" in value;
}
function foo<T extends A | B, K extends keyof T>(value: T, key: K) {
if (isA(value)) {
value["a"] + 1; // OK, value["a"] is number
value[key] + 1; // Error. What type should key be to make this line valid?
}
} |
This error being misleading is one of my pet peeves (it says “not assignable” which is not strictly true when just looking at the types involved), but the full error text does hint at what’s really wrong:
…meaning the assignment was rejected because you tried to assign a fresh object literal with too many properties for the type it’s being assigned to. This check only applies to directly-assigned object literals; a regular type error will not include this text. It is meant to 1) catch typos and 2) prevent you from specifying properties that you’ll immediately lose access to. |
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
🔎 Search Terms
union; widen; type
🕗 Version & Regression Information
⏯ Playground Link
Playground link with relevant code
💻 Code
The Handbook describes the union type:
This means if we define
type T = A | B
, then its value can be any ofA
's values, or any ofB
's values. It implicitly means that if a value is not of typeA
orB
, it is not a validT
value.However, the code below shows that the same value is considered not
A
and notB
, but isA | B
. This contradicts the Handbook. One of them needs to changed to match the other. To me, the Handbook seems to make more sense.🙁 Actual behavior
A value of
A | B
can be neitherA
norB
.🙂 Expected behavior
A value of
A | B
should be eitherA
orB
.The text was updated successfully, but these errors were encountered: