Let's start with an apology for the overly generic question, but I am wrecking my head how to narrow it down due to lack of understanding of what's happening here, so will adjust based on comments / answers.
I have created a sample program on TypeScript Playground that should not compile but does (using latest version of TypeScript, v4.5.2 as of this writing.) I am trying to understand why this compiles in order to understand what other bad programs might sneak past the type checker and go undetected. Here is another version of the program that shows the problem at runtime. Are there any options I have overlooked or anything I can do to have this program not type check?
For convenience, I inline the program in question here as well:
type Settings = { 'a': boolean; 'b': string }
function setSetting<K extends keyof Settings>(p: K, v: Settings[K]): void {}
// setSetting('a', 100) // good; it fails
setSetting('a', true); // good; compiles
function breakSetSetting(k: keyof Settings, v: boolean): void {
setSetting(k, v);
}
breakSetSetting('b', true); // bad; it compiles!
Update: As per comment by @crashmstr using generics for breakSettings makes the program not compile, however, it's still unclear to me why it was allowed to compile before.
v. As it is, the most the compiler knows is that the call intosetSettingthere is astring | boolfor the second parameter and thevdoes "work" for that.