Consider the scenario where the following code is implemented:
const myObj = {
"hello": "world";
} as const;
const anyString: string = "Hi"
if (myObj[anyString]) { // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ readonly hello: "world"; }'.
console.log('Property exists!', anyString)
}
The error message it generates appears to be misleading since the type declaration of myObj
ought to resemble this:
interface TMyObj {
[specificKeys: "hello"]: "world",
[otherKeys: string]: undefined
}
Nevertheless, the error occurs due to distrust in the [otherKeys: string]: undefined
section, under the impression that random keys could be added.
Although this is actually safeguarded against, as adding random keys would result in a type-error like so:
myObj.bar = "other value" // Property 'bar' does not exist on type '{ readonly hello: "world"; }
Is there a method to craft secure type-checked code in this instance without converting anyString
into a key of myObj
? Because such conversion is not guaranteed.
This situation appears to be one that should ideally be addressed by as const
.