-
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
Discriminated unions is not work when field key is number #57245
Comments
It seems that there is no restriction in the documentation that keys must be strings. |
It's not about the keys being strings or not - discriminants must be literal-typed. |
|
This is the first I'm seeing that |
Narrowing via type on discriminated unions works by looking for properties that look like discriminant properties... but |
One strange thing here is that if it's not a type A = ({ [0]: number } & number[]) | ({ [0]: boolean } & boolean[])
declare const a: A
if (typeof a[0] === 'number') {
console.log(a)
// ^? { [0]: number } & number[]
}
if (typeof a[0] === 'boolean') {
console.log(a)
// ^? { [0]: boolean } & boolean[] If we replace type A = ({ [0]: number } & number[]) | ({ [0]: string } & string[])
declare const a: A
if (typeof a[0] === 'number') {
console.log(a)
// ^? A
}
if (typeof a[0] === 'string') {
console.log(a)
// ^? A |
π Search Terms
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play?#code/C4TwDgpgBAglC8UB2BXAtgIwgJwNoF0oAfKAZ2GwEskBzAgKHtEigCEEoBvKABgC5k6LNgA0UAIYCAjFAC+xLrwHkqtMZKgByKZrmMAJhADGAG3HZoRgPZJyEgTHqHT5yzbsYBrRpQBmUAApmCCt-cVweQnhorVRMHE0ASi56KDSoa1srEwgAOhMrGgDxRNT0gHpy9Or0gD0AfnpZej9A4NCoDFxNcU0omM044SSU6szSbLyCooxS6sqamoamlv8g8BD-Ls0ePoQBoYTkzjK08cn8woDZ06gFxbrG5tb1yA6uyP3EQaEj0fTzjlLjM5hUqg80stmkA
π» Code
π Actual behavior
Unable to type guard
b
as an option of the union typeB
.π Expected behavior
Type
b
as{ 0: number, a: 1 }
when type guarding it withtypeof b['0'] === 'number'
.Additional information about the issue
The text was updated successfully, but these errors were encountered: