Unfortunately, TypeScript does not offer support for a stricter interpretation of the `any` type where member access is restricted unless it is deemed safe. There hasn't been any formal request for this feature either. While there was a proposal for `--strictAny`, it was eventually closed in microsoft/TypeScript#24737, with the reason being that adding extra complexity to the `any` type didn't seem warranted, especially given that `any` is often used intentionally to disable type checking in certain real-world scenarios.
Instead of waiting for TypeScript to introduce such functionality, you could consider utilizing a linter like TypeScript ESLint. The `no-unsafe-member-access` rule specifically prohibits unsafe member access on variables typed as `any`. However, be aware that this may lead to unwanted errors even in situations where proper type checking has been implemented, making it more restrictive than desired.
declare const myObject: any;
myObject.myProperty // warning: unsafe access 😊
myObject?.myProperty // warning: unsafe access ☹
If you find yourself in this situation, one workaround could involve copying the value to a variable of a non-`any` type:
type MyAny = { [k: string]: any } | undefined | null;
const _myObject: MyAny = myObject
_myObject.myProperty; // error
_myObject?.myProperty; // okay
Alternatively, you could create a type checking function to narrow down the `any` type to a more safely indexable type:
function nonNullish(x: any): x is { [k: string]: any } {
return x != null;
}
if (nonNullish(myObject)) {
myObject.myProperty // okay
}
Another approach could involve discussing with the typings provider for the library to emphasize that using `any` might be too loose of a type, especially if the value could potentially be `undefined` or `null` at runtime. If that's not an option, then perhaps accepting and monitoring potential issues until they actually occur might be the way to go.
TS-ESLint Playground link to code