const o1 = { f: () => 1 }
const keys1 = Object.keys(o1) // ['f']

class C { f() {} }
const c1 = new C()
const keys2 = Object.keys(c1) // []

The following ObjectKeys returns ['f'] for class C. This is my problem.

type ObjectKeys<T> = T extends object ? { [Key in keyof T]: Key }[keyof T] : never

function objectKeys<T>(o: T) {
  if (o === undefined || o === null) {
    return []
  }

  return (Object.keys(o) as any) as ReadonlyArray<ObjectKeys<T>>
}

const keys3 = objectKeys(o1) // Return type is ['f']
const keys4 = objectKeys(c1) // Return type is ['f'], but the value is []

I know TypeScript can never know if a property is hidden or not. But I would like to get rid of those class method names that we know are not visible for Object.keys(o).

0 Answers