Using multiple extra accessors causes type errors arising from union types
See original GitHub issueDescribe the bug 🐛
In TypeScript, if I attempt to use two extra accessors with different return types, the types for the computed values seem to be a union over the return types of all of the extra accessors, rather than just the return type of the accessor in use.
(Related: those types also include undefined
, even in cases where the value is required
, which seems wrong — but that’s a separate issue I guess.)
To Reproduce 📝
Here we use the asEmail
example given in README.md
, and we add another extra accessor called asZero
which always returns zero. So the type for asEmail
is string
, and the type for asZero
is number
:
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 asZero: ExtensionFn<number> = (value) => 0;
const env = from(process.env, {asEmail, asZero})
Then the type required for a value using either of these extra accessors is number | string | undefined
, so I have to write the following:
const validEmail: number | string | undefined = env.get('ADMIN').asEmail()
const zero: number | string | undefined = env.get('ADMIN').asZero()
Expected behaviour 🤷♂️🤷
I would expect this to work / not fail type checking:
const validEmail: string | undefined = env.get('ADMIN').asEmail()
const zero: number | undefined = env.get('ADMIN').asZero()
(In fact, as mentioned above, I’d love to not have to include undefined
here; AFAICS asEmail
always either returns a string or raises an error, so why not…
const validEmail: string = env.get('ADMIN').asEmail()
const zero: number = env.get('ADMIN').asZero()
… but again, that’s secondary to the issue I really want to raise, which is the union thing.)
Environment (please complete the following information) 💻:
- OS: macOS Mojave 10.14.6
- Runtime: Chrome 79.0.3945.130
- Version 6.0.4
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:8 (6 by maintainers)
@gimbo I’ve fixed the
undefined
now also, thank you!@evanshortiss Hi Evan - didn’t get chance to look at this over the weekend but I’ve just just checked and it does indeed seem to be fixed for my use case. The
undefined
s are still there but thenumber
/string
clash is gone. Thanks!