Type narrowing is working with [] operator and not with Array.at

12 hours ago 3
ARTICLE AD BOX

First, playground

https://www.typescriptlang.org/play/?target=99&ts=6.0.2#code/C4TwDgpgBAMglgZ2ASWBAtlAvFA3gKCigEMAuKJAJzgDsBzQqAI3JoFd0mJL8BfffAHpBoSFAAKlAPZgE2WIhRp0AbQC6UAD4KkqDOvX5R0STLk4AgpUrEQAHni7lAPi1QrN+x9sPFe9M7OAgBmbDQAxsBwUjRQaEhQABRgxDbo5KayAJR4jHDBiQDkxIVQtFApaSoADGo5BERE4TEJcMrkjkoY8pXEqrWM-IzNNAnBcJROGADykDbAUpQdfspu3vad-q44vf1qwy3AUOOTXegWwMtTmNrrvteu2mEAJhDjNBDPPal9AHTEwES1SyAiI+US61+iHWyR+eyy9UYTUOZXaOjO6m+VQGRCGYIKkOh1lssLS-0BwIRuUaUGEUAA6gALEBQbjSShQRncCAAfiRUBGrTRm2UmJ2cPJQJBuL4QA

Then, code

type ListItem = { a: string b: number } //type Props = ListItem[] | ListItem[][] type Props = Array<ListItem> | Array<Array<ListItem>> function test (param: Props) { if('a' in param[0]) { const item: ListItem = param[0] } const firstItemOperator: ListItem | Array<ListItem> = param[0] const firstItemAt: ListItem | Array<ListItem> | undefined = param.at(0) if(Array.isArray(param[0])) { const item: ListItem[] = param[0] } if(Array.isArray(param.at(0))) { // Why error here? const item: ListItem[] = param.at(0) } }

Finally, question

Why type narrowing is working with [] operator, and not with at() function?

There are related topics

https://github.com/microsoft/TypeScript/issues/53395 It seems in an issue with ReadonlyArray, which I explicitly removed for testing

Otherwise, I don't understand the difference. I have a workaround, but I really need to know why it's not working as I expect.

Read Entire Article