[TS] Type narrowing string union?

I have the following setup;
const fn = (source: keyof typeof Obj | "$none") => {
if (source in Obj) Obj[source];
// ^^^^^^^^^^^
// Element implicitly has an 'any' type because expression of type [...] can't be used to index type [...]
// more code...
}
const fn = (source: keyof typeof Obj | "$none") => {
if (source in Obj) Obj[source];
// ^^^^^^^^^^^
// Element implicitly has an 'any' type because expression of type [...] can't be used to index type [...]
// more code...
}
I also have the following relevant compiler options;
"strict": true,
"alwaysStrict": true,
"keyofStringsOnly": true,
"moduleResolution": "node",
"module": "esnext",
"target": "esnext"
"strict": true,
"alwaysStrict": true,
"keyofStringsOnly": true,
"moduleResolution": "node",
"module": "esnext",
"target": "esnext"
Is there a way that I can prevent the error from occuring and have typescript correctly narrow source's type from keyof typeof Obj | "$none" to keyof typeof Obj? I would have thought that if (source in Obj) then obviously typeof source === keyof typeof Obj, if not directly then due to Obj's keys definitely including source. I can't figure out how to narrow it, I've tried .startsWith("$") but for some reason that's still not a type predicate to a ${arg0}${string} literal, Object.keys(Obj).includes(source) is just an ugly equivalent to the codeblock above, source[0] === "$" doesn't work. Nothing except Obj[source as keyof typeof Obj] seems to work, which is not only ugly but entirely defeats the purpose of using typescript there.
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server