0

Why does using the any type disable strict null checks in the below code? Is this a bug?

type SomeType = any;

interface Optional {
  some?: { 
    key: SomeType;
  };
}

interface NotOptional {
  key: SomeType;
}

const opt: Optional = {};

const val: NotOptional = {
  key: opt.some?.key // no error if SomeType is any
}

Playground

NoBullsh1t
  • 483
  • 4
  • 14
  • 3
    `any` is an escape hatch from the type checking system. So, it works as expected - it prevents TS from properly evaluating types. – VLAZ Oct 12 '22 at 10:08
  • Apparently I have to inflate my mental image of how bad `any` is. If `opt.some` had already been `any`, then I'd have expected this problem. But on this level? jeez... – NoBullsh1t Oct 12 '22 at 10:59
  • It's pretty bad, yes. I'd recommend avoiding it as much as possible. Not *entirely* as some cases you may need to handle an `any` value for a short amount of time (e.g., common if you want to make a type guard) but that's limited. `any` should not really crop up in most other cases. When you *do* need a value to represent something that you don't know, then use `unknown`. It acts as `any` as it accepts anything assigned to it, however, when used it always requires validation. It's therefore safer. Doesn't bypass the type system. – VLAZ Oct 12 '22 at 11:02
  • Yes, I'm aware of `unknown`. Unfortunately this `any` comes from code outside of my control. I had to copy that interface and make it use generics to avoid this problem. Really clumsy... – NoBullsh1t Oct 12 '22 at 15:55

1 Answers1

1

It works as expected since that's how any is meant to work.

Poltix
  • 61
  • 8