Closed Mathias-S closed 11 months ago
It's string[]
. There is definitely no undefined
in it.
Agree with @ArthurKa, I don't see this widening as being useful.
I would agree with @Mathias-S that it would be really helpful, as it prevents additional runtime code only "caused" by the use of typescript:
function doStuff(ids: string[], activeId?: string) {
// required TS code
const activeIndex: number = activeId === undefined ? -1 : ids.indexOf(activeId);
// valid JS code (with the same result)
const activeIndex = ids.indexOf(activeId);
}
I would agree with @Mathias-S that it would be really helpful, as it prevents additional runtime code only "caused" by the use of typescript:
function doStuff(ids: string[], activeId?: string) { // required TS code const activeIndex: number = activeId === undefined ? -1 : ids.indexOf(activeId); // valid JS code (with the same result) const activeIndex = ids.indexOf(activeId); }
And what about
function doStuff(ids: string[], activeId?: string | number) {
Allow number
also? No. It doesn't seem to be right for me. You need some point to stop widening. Just string
looks good to me.
Lots of JS valid code is not valid for TS type system. It's the main idea of TS. To restrict a lot of permissiveness.
IMO there is a difference between allowing undefined
and allowing another type.
The widening for undefined
handles somehow the "optional" behaviour of the indexOf
argument.
Shouldn't it be possible to use
undefined
as the first argument ofarray.includes
andarray.indexOf
?Consider the following example:
This happens quite a few times in a codebase I'm working on. Some workarounds include:
The last workaround using TypeScript's
!
non-null assertion works, but violates @typescript-eslint/no-non-null-assertion which is part of typescript-eslint's recommended config. Also,!
wouldn't work in the following case:Is there any benefit to disallowing
undefined
as thesearchElement
inarray.includes
?I don't see any drawbacks to allowing it, but there are some clear benefits that I believe are in line with ts-reset's philosophy.