В typescript, как индексировать защищенную/частную собственность с именем свойства из параметра метода (т. е. внешней области)

#typescript

Вопрос:

 class A {
  protected x: number // or private 
  protected y: string // or private 

  public a: number
  public b: string

  public get<T extends 'x' | 'y'>(prop: T) {
    return this[prop] // ERROR: Type 'T' cannot be used to index type 'this'.ts(2536)
    // 'prop' is from outer scope, it's prevented to index protected/private properties.
  }
  public get2<T extends 'a' | 'b'>(prop: T) {
    return this[prop] // public property is ok.
  }
  public get3<T extends 'x' | 'y'>(prop: T) {
    return this[prop as 'x' | 'y'] 
    // this is ok, but not exact, prop is not determined to be a specific enum item.
  }
}

const a = new A()

a.get2('a') // number
a.get3('x') // string | number

 

Как показано ранее, в get методе prop из внешней области запрещено индексировать защищенные/частные свойства.

Итак, как сделать это возможным?

Комментарии:

1. частные/защищенные свойства не индексируются. keyof A вернет все ключи, кроме protected/private