代码之家  ›  专栏  ›  技术社区  ›  left click

我可以将获取值的对象类型的模式应用于类的非静态成员吗?

  •  1
  • left click  · 技术社区  · 6 年前

    我经常用这种模式。

    const numbers = { a: 1 as 1, b: 2 as 2 },
          number: typeof numbers[keyof typeof numbers] = 1; // type of number is (1 | 2)
    

    但我不能把它应用到课堂上,所以我质疑。

    class Class {
        numbers = { a: 1 as 1, b: 2 as 2 };
    
        method () {
            const number: this['numbers'][keyof this['numbers']] = 1, // Error: Type '1' is not assignable to type 'this["numbers"][keyof this["numbers"]]'.
                  number2: typeof this['numbers'][keyof typeof this['numbers']] = 1; // Error: Cannot find name 'this'. 
        }
    }
    

    你知道怎么做吗?请告诉我。谢谢。:)

    1 回复  |  直到 6 年前
        1
  •  2
  •   jcalz    6 年前

    Polymorphic this 不是你真正想用的。例如,对于 Class 缩小 numbers 然后 this['numbers'] 不一定有一个属性 1 :

    class Whoops extends Class {
      numbers = {a: null! as never, b: 2 as 2, c: 3 as 3}
    }
    

    而不是使用 键入,只需显式命名类:

    const number: Class['numbers'][keyof Class['numbers']] = 1; // okay
    

    而且,因为这种模式 BlahBlahBlah[keyof BlahBlahBlah] 是多余的,并且经常使用,我倾向于给它一个类型别名:

    type ValueOf<T> = T[keyof T];
    

    然后你可以改变上面的 number 键入批注到:

    const number: ValueOf<Class['numbers']> = 1; // okay
    

    希望能有所帮助。祝你好运!