-
Notifications
You must be signed in to change notification settings - Fork 12.8k
typeof on object index access types don't include undefined when noUncheckedIndexedAccess #42471
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
But why? Your array only stores Note that If
|
i don't understand why the type would be different when accessing it vs when using |
Accessing array element returns a union with Note that explicitly assigning
|
This is currently the intended behavior and not a bug; see #39560
Perhaps this should be rephrased as a feature request? |
I see. Would anybody happen to know how to create a type with For example, I'm writing a bunch of helper functions to make working with export function lengthGreaterThan<T, L extends number>(
arr: Readonly<T[]>,
length: L
): arr is [...TupleOf<T, L>, T] & T[] { //see https://github.com/microsoft/TypeScript/issues/26223#issuecomment-674514787
return arr.length > length
} which means you no longer have to check for if (lengthGreaterThan(foo, 3)) {
const a: string = foo[0] //no error
const b: string = foo[3] //no error
const c: string = foo[4] //Type 'string | undefined' is not assignable to type 'string'
} How would I make a type for a I tried |
i think i figured out a way to do it if anybody is curious const indexedAccessCheck = ([] as never[])[0]
export type NoUncheckedIndexedAccess = undefined extends typeof indexedAccessCheck ? true : false
export type TupleOfUpTo<T, L extends number> = TupleOf<T, L> | (NoUncheckedIndexedAccess extends true ? [] : never)
export function lengthLessOrEqual<T, L extends number>(arr: Readonly<T[]>,length: L): arr is TupleOfUpTo<T, L> {
return arr.length <= length
} i've done minimal testing though, there's probably a lot wrong with it |
This issue has been marked as 'Question' and has seen no recent activity. It has been automatically closed for house-keeping purposes. If you're still waiting on a response, questions are usually better suited to stackoverflow. |
Bug Report
π Search Terms
noUncheckedIndexedAccess
π Version & Regression Information
4.2.0-dev.20210124
β― Playground Link
https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&ts=4.2.0-dev.20210124#code/CYUwxgNghgTiAEYD2A7AzgF3gMyUgXPCgK4C2ARiDANoC6AsAFBMYCeADggGJ7wC88NpyTYceagEZa8APQySFKkybJ0WcrEI8k-MUknS5AFQ4IA5Asox4AH3jEUobAEsUIYGfjO0RJFihoaM4A5ihQ5BAIGDpC5pZUZkA
Playground link with relevant code
π» Code
π Actual behavior
typeof foo[1]
returnsnumber
, but the actual type isnumber|undefined
π Expected behavior
typeof foo[1]
should returnnumber | undefined
whennoUncheckedIndexedAccess
is enabledThe text was updated successfully, but these errors were encountered: