3

The type {}(empty type) is almost a super type which every raw type extends it. My question is why the type {[x:string]:number} extends {}? The following type is always true:

type X =  {} extends {[x:string]:number} ? true : false
Boann
  • 48,794
  • 16
  • 117
  • 146
Majid Majed
  • 326
  • 2
  • 12
  • I think because of this https://github.com/microsoft/TypeScript/issues/15300 and this https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript#answer-64971386 – captain-yossarian from Ukraine Oct 04 '21 at 09:59
  • It's all about differences between interface and type declarations. My question is what's exactly the type {[x:string]:number}? Is it a type with infinite number of properties? or it is an empty type. To be clarify consider the following code: type T1='a'|'b'; type T2 = {[t in string]:number}; type T3 = {[t in T1]:number}; const x:T2={};// fine const y:T3={}// error! why? – Majid Majed Oct 04 '21 at 12:17
  • `T3` expects `a` and `b` prop and you did not provide them to `y` – captain-yossarian from Ukraine Oct 04 '21 at 12:30
  • I know but {[x:string]:number} also says the objects of this type must have at least a property of type number and still we can assign an empty object to a variable of this type. – Majid Majed Oct 04 '21 at 13:27
  • 1
    That's not what that type says; it says that the type is indexed by string keys with numeric values. Having no such key is entirely valid. – Ingo Bürk Oct 04 '21 at 13:31
  • "Having no such key is entirely valid", can you supply any reference to this? – Majid Majed Oct 04 '21 at 21:09

0 Answers0