Types for extra accessors suggest they can't be used with default() or required() (though they can)
See original GitHub issueDescribe the bug 🐛
In TypeScript, if I attempt to use an accessor defined via the extraAccessors
machinery in conjunction with default
or required
, TypeScript complains; in strict mode at least, it’s a compilation error.
It’s possible to work around this with as any
, but perhaps the type definitions could be fixed so that’s not necessary.
When I first noticed this, I concluded that extra accessors couldn’t be used with default
or required
at all and nearly gave up on them; luckily I realised it might just be a typing problem, and that turns out to be true.
(BTW, I mention default
and required
but I suspect this may also be true for convertFromBase64
and example
.)
To Reproduce 📝
README.md
gives this example of using extraAccessors
with TypeScript:
import { from, ExtensionFn, EnvVarError } from 'env-var'
process.env.ADMIN = 'admin@example.com'
const asEmail: ExtensionFn<string> = (value) => {
const split = String(value).split('@')
if (split.length !== 2) {
throw new Error('must contain exactly one "@"')
}
return value
}
const env = from(process.env, {asEmail})
env.get('ADMIN').asEmail()
That works, but either of the following lines:
env.get('ADMIN').default('me@example.com').asEmail()
env.get('ADMIN').required().asEmail()
cause compilation to fail with this error:
Property 'asEmail' does not exist on type 'IPresentVariable'. TS2339
The workaround is of course to relax the types, e.g.:
(env.get('ADMIN').default('me@example.com') as any).asEmail()
(env.get('ADMIN').required() as any).asEmail()
That all seems to work as expected (by which I mean the expected semantics of default
and required
seem to be respected), but it’s a bit ugly.
Expected behaviour 🤷♂️🤷
Just that the above works without a compilation error. Obviously the accessor names are arbitrary and can’t be known to the library, so perhaps there just needs to be a more relaxed type in use for extra accessors (and some modification of ExtensionFn
accordingly?) — but I’m waving my hands around here, if I’m honest. 🤪
Environment 💻:
- OS: macOS Mojave 10.14.6
- Runtime: Chrome 79.0.3945.130
- Version 6.0.1
Additional context
When @xuo opened issue #83, he mentioned that:
extraAccessors are not chainable with required()
but wasn’t the core topic of that issue and wasn’t addressed at that time; it certainly looks now like they can be chained, so I wonder if @xuo made the same mistake I almost made, of seeing the type error and assuming that it just doesn’t work (even though it seems to).
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (3 by maintainers)
Just got round to trying this out, and I can report that it looks good at my end! 😃 Many thanks.
@gimbo published a fix in 6.0.3