I do have a real-world circumstance where I needed to refer to a property by name using a string literal. I wanted to make that type-safe, and it feels like in TypeScript, that should be possible. Consider the following simplified example:
interface MyInterface {
foo: string,
}
const barName = <keyof MyInterface>'bar' // No error?
const bazName = 'baz' as keyof MyInterface // No error?
const bopName:keyof MyInterface = 'bop' // Finally, an error!
I believe the answer is that the <> and as operations in TypeScript are "type assertions" not "type cast attempts". The first two consts above are basically saying, "trust me, this is a key of MyInterface", while the third const is attempting a typed assignment, and failing.
I'd like to know if I'm right about that, and if so, if there's some other in-line way to test that a string literal is a keyof a given interface, without making a temp variable.