1

typeof M is 0, typeof P is 1, I think both types should be 1, number and object do not intersect

type M = 1 & {} extends never? 1 : 0;

type P = 1 & object extends never? 1: 0;
Inigo
  • 12,186
  • 5
  • 41
  • 70
math-chen
  • 31
  • 2
  • 2
    At least related: https://stackoverflow.com/questions/47339869/typescript-empty-object-and-any-difference – T.J. Crowder Dec 14 '21 at 08:14
  • `object` represents all non primitive values. `1 & object` resolves to `never`. Which in turn gives you `type P = never extends never? 1: 0; // 1` – captain-yossarian from Ukraine Dec 14 '21 at 08:25
  • Also please read [wiki](https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-all-types-assignable-to-empty-interfaces) – captain-yossarian from Ukraine Dec 14 '21 at 08:38
  • @captain-yossarian - Is it fair to say that `1 & {}` and `1` are equivalent? ([related playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBAGlC8UCMUIA9gQHYBMDOyUAZFAN4C+UA-FAEQgR61QBcdWA9rQNwBQA9PyjCAelV6hIUAJoJCJCqgzZ8hGvUbM2tTjwFDRVIA)) Since TypeScript's type system is structural and `{}` has no members? – T.J. Crowder Dec 14 '21 at 08:47
  • 2
    @T.J.Crowder I treat it as `1+0===1` and `0+1===1`. As per my understanding `{}` is a supertype for every value which has some properties in a prototype chain. except `null` and `undefined` because they don't have any properties. P.S. I can't say whether it fair or not because I don't know how TS treat this type under the hood – captain-yossarian from Ukraine Dec 14 '21 at 09:03
  • 2
    @captain-yossarian - Thanks, yup, that's basically what I meant. – T.J. Crowder Dec 14 '21 at 09:09
  • @captain-yossarian I checked just now and apparently `{}` also matches types like `number` and `boolean` (even though they aren't `object` values/types, but they do inherit members like `toString()` from their prototype, but I found articles ([like this one](https://mariusschulz.com/blog/the-object-type-in-typescript)) which implies `{}` _shouldn't_ match primitive types - so I can see why people would get confused). – Dai Dec 14 '21 at 10:46
  • @Dai I think this is because TS should be consistent with javascript. Since each value in javascript is de-facto is an object, primitives are assignable to `{}` because they also represent an object. Only my guessing – captain-yossarian from Ukraine Dec 14 '21 at 11:02

0 Answers0