wojtekmaj / get-user-locale

A function that returns user's locale as an IETF language tag, based on all available sources.
MIT License
58 stars 9 forks source link

Type error: Object is possibly 'undefined' #51

Closed bravo-kernel closed 1 year ago

bravo-kernel commented 1 year ago

Any pointers on what might cause below CI error when using v2.1.1:

5:38:43 PM: #9 1.141 info  - Linting and checking validity of types...
5:38:55 PM: #9 13.14 Failed to compile.
5:38:55 PM: #9 13.14 
5:38:57 PM: #9 13.14 ./node_modules/get-user-locale/src/index.ts:23:29
5:38:57 PM: #9 13.14 Type error: Object is possibly 'undefined'.
5:38:57 PM: #9 13.14 
5:38:57 PM: #9 13.14   21 | 
5:38:57 PM: #9 13.14   22 |     const splitEl = el.split('-');
5:38:57 PM: #9 13.14 > 23 |     return `${splitEl[0]}-${splitEl[1].toUpperCase()}`;
5:38:57 PM: #9 13.14      |                             ^
5:38:57 PM: #9 13.14   24 |   });
5:38:57 PM: #9 13.14   25 | }
wojtekmaj commented 1 year ago

Hmmm... The error does make sense to me. String.split() returns an array of strings and the second element of this array indeed can be undefined

But:

This is a false positive because of this protective measure just above:

https://github.com/wojtekmaj/get-user-locale/blob/14eb2a61f17172dab3f735aac8f818ab4913afcb/src/index.ts#L18-L20

but I would still like to know more.

bravo-kernel commented 1 year ago

Thanks for responding. I am using Typescript 4.9.4 and will try to follow-up on your questions.

bravo-kernel commented 1 year ago

I have created a fresh project at https://github.com/bravo-kernel/debug-get-user-locale.

Then added get-user-locale line here.

If you run npx tsc you will see the error.

wojtekmaj commented 1 year ago

Aaaah, thank you for this.

The key here is noUncheckedIndexedAccess. When turned on, you'll get the error. TypeScript disregards the safety checks I have put in place and throws this error.

Related: https://github.com/microsoft/TypeScript/issues/41638

bravo-kernel commented 1 year ago

Cool, good that we both are seeing the same. Are you suggesting that I turn off noUncheckedIndexedAccess (which is not an option)?

wojtekmaj commented 1 year ago

Not at all :D Just thinking out loud.

wojtekmaj commented 1 year ago

Released in v2.1.2. Thank you for this!

bravo-kernel commented 1 year ago

Perfect, much appreciated 💃