TypeScript's type system isn't perfectly sound and has (largely intentional) holes where you can sneak through unsafe things. Conversely there are places where soudness is enforced, but in a way that is often unhelpful to developers who then need to use type assertions or other loopholes to work around them. Idiomatic TypeScript can often be unsafe; safety is often regained only at the expense of jumping through seemingly unnecessary hoops; and the safety is sometimes illusory.
My point: your "hacky" solutions are essentially fine as long as you're aware of their limitations. You can sometimes rewrite these assertions so that they are not lies, but you are not really prevented from lying. As long as you can limit the scope of any potential lies so that they don't easily spread to other code, you're probably doing something reasonable.
Let's look at some other possible solutions. The following is probably as safe as I can imagine:
function lookup1(key: string) {
return (key === "A" || key === "B") ? MAPPING[key] : 0; // no lies, but redundant
}
Here you are explicitly comparing key
to the literal strings "A"
and "B"
. It does involves duplication at runtime, which might be worse than using a type assertion, but there's no obvious way I can think of to fool the compiler here. So you get safety in exchange for some not-very-scalable hoop jumping.
So why can't you just check key in MAPPING
? It's because object types in TypeScript are open and not exact. TypeScript knows that MAPPING
contains A
and B
keys. It does not know that it lacks all other keys. As far as the compiler is concerned, it is possible that MAPPING
has keys C
and D
keys of, say, string
type:
type MappingType = { A: number, B: number };
const weirdMapping = {A: 1, B: 2, C: "three", D: "four"};
const MAPPING: MappingType = weirdMapping;
So just checking key in MAPPING
does not imply that you've checked if MAPPING[key]
is of type number
. And for similar reasons, Object.keys(MAPPING)
is considered to be type string[]
and not Array<"A" | "B">
. This is one of those places where the compiler enforces soundness in a way that feels unhelpful a lot of the time.
If you want to tell the compiler not to worry about this problem (and take the responsibility for preventing these edge cases yourself), you can use a type assertion like this:
function lookup2(key: string) {
return (key in MAPPING) ? MAPPING[key as keyof typeof MAPPING] : 0;
}
or you could make a user-defined type guard which allows you to assert to the compiler that a boolean
-returning function acts as a check on one of its arguments:
function lookup3(key: string) {
// user defined type guards are not safe either, much like type assertions
function isKeyOf<T>(obj: T, k: PropertyKey): k is keyof T {
return k in obj;
}
return isKeyOf(MAPPING, key) ? MAPPING[key] : 0;
}
Both the type assertion and the user defined type guard allow you to lie to the compiler. As long as we're sure that MAPPING
only contains A
and B
keys, then we haven't actually lied. Whether or not this is more or less hacky than your code in the question is subjective.
The other thing you could do is along the lines of your second solution, but instead of widening MAPPING
itself, create a new wider variable and assign MAPPING
to it:
function lookup4(key: string) {
const MAPPINGWIDE: { [k: string]: number | undefined } = MAPPING;
return MAPPINGWIDE[key] || 0;
}
Here MAPPINGWIDE
only exists inside the lookup
function, but we've told the compiler that all its properties are either number
or undefined
. The compiler allows us to assign MAPPING
to it without any kind of assertion or loophole. If you change MAPPING
to be const MAPPING = {A: 1, B: 2, oops: "hello"}
the compiler will complain in your MAPPINGWIDE
assignment. So it's only a little redundant (we have to copy MAPPING
), and PERFECTLY SAFE, right?
Well, maybe not. Note that if you define MAPPING
via weirdMapping
above, then the code still compiles with no error. You can widen weirdMapping
to MappingType
and then assign the MappingType
to MAPPINGWIDE
, even though this is unsafe. And so lookup4("C")
will produce a string
value at runtime that the compiler thinks is a number
. The code lookup4("C").toFixed()
will blow up at runtime with no compiler warning.
This is the "sometimes illusory" type safety. Is it likely to be an issue? Probably not. But it's a judgment call whether this solution is any more or less hacky than the others.
Okay, hope that gives you some direction and possibly a different perspective. Good luck!
Playground link to code