获取没有初始化值的类实例上的属性的键

时间:2019-09-28 00:36:24

标签: typescript

我试图获取存在于类中的属性键的值。该属性没有初始化程序。

(在我的实际情况下,该值是在装饰器中异步设置的)

沙箱 https://repl.it/repls/BuzzingSadSourcecode

class Thing {
  findme: string
}

const thing = new Thing()

console.log(
  getClassKeys(thing).includes('findme') // should be true
)

我当前的getClassKeys()函数实现:

const getClassKeys = (instance: any) => {
  const ignored = ['constructor', 'length', 'prototype']
  const items = [
    ...Object.getOwnPropertyNames(instance.constructor.prototype),
    ...Object.getOwnPropertyNames(instance),
  ]
  return items
    .filter(item => !ignored.includes(item))
}

0 个答案:

没有答案