1

I want to do this.

type LengthOfObject<T> = ...

type Target = {
  a: "a",
  b: "b",
  c: "c",
}

type len = LengthOfObject<Target>  // 3

I tried below code, but not worked well.

type LengthOfObject<T> = (keyof T)["length"] 
// LengthOfObject<Target> // number

type LengthOfObject<T> = [(keyof T)]["length"] 
// LengthOfObject<Target> // 1

How to get key length of object type?

shshsh12
  • 125
  • 1
  • 1
  • 12
  • ① This looks like it might be an [XY problem](https://en.wikipedia.org/wiki/XY_problem), since objects can have more properties than TS knows about, or even fewer given the existence of optional properties; what would you be using it for, could you [edit] to clarify the use case? There might be something more appropriate. – jcalz Apr 15 '23 at 12:09
  • ② Generally speaking TS doesn't want you to iterate through unions; you can do it the supportable way which doesn't scale, or a scalable way which isn't supported. ⊛ See [this playground link](https://tsplay.dev/mL802m) to see what I'm talking about. Does that fully address your question? If so I'll write up an answer explaining; if not, what am I missing? – jcalz Apr 15 '23 at 12:09
  • You could use [UnionToTuple](https://stackoverflow.com/questions/55127004/how-to-transform-union-type-to-tuple-type) to generate a Tuple from the keys and than checking the length – Filly Apr 18 '23 at 08:26

0 Answers0