-
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
Should/could typeguarding work on arrays/length #10272
Comments
Strictly speaking - no. It doesn't guard against sparse arrays, e.g: const arr: number[] = [];
arr[1] = 5;
if (arr.length) {
arr.shift(); // undefined
}
arr.shift(); // 5 Then again, the true type of indexing is also |
@gcnew Thanks for the explanation, but then shouldn't accessing sparse arrays and having
|
@wallverb Yes, well and truly. It was done for convenience as explained by the reply to #7140 (comment) PS: To play devil's advocate, I guess the return type of |
wow, interesting, thank you so much for finding that comment for me. I wish such knowledge was more easily accessible/findable :) |
BTW: as a workaround this works: function isShiftable<T>(arr: T[]): arr is Array<T> & { shift(): T; } {
return !!arr.length;
}
const arr: number[] = [5];
if (isShiftable(arr)) {
const x = arr.shift(); // x is of type `number`
} |
This workaround is not working for me. function isNotEmpty<T>(arr: T[]): arr is Array<T> & { pop(): T; } {
return arr.length > 0;
}
function doSomething () {
const stack: Vertex[] = []
const groups: string[] = []
// put some things on the stack
while (isNotEmpty(stack)) {
const v = stack.pop() // v is still typed as Vertex | undefined
groups.push(v.id) // [ts] Object is possibly 'undefined'
}
} did I miss something? (tried this with typescript 2.0.3 and 2.1.0-dev.20160924) Update: changed the order of the return type def like so: function isNotEmpty<T>(arr: T[]): arr is { pop(): T; } & Array<T> and it works as desired. Is the type intersection operator not commutative? |
@dlmanning You are right, the suggested fix is the the way to go. It should be noted though that this type guard is a hack - I just found that it worked. About the type intersection operator I don't think there is a notion of commutativity, I suspect it's just the compiler picking the first matching declaration. |
TypeScript Version: @next
Code
The text was updated successfully, but these errors were encountered: