1

在方法类型签名中,类型keyof this可用于将参数约束为类的有效键的字符串名称。但是,如果该方法采用选项样式而不是位置参数,则它不起作用。IE:

class Foo {
  // Allowed
  m1(a: string, b: keyof this) {
    ...
  }

  // Error: A 'this' type is available only in a non-static member of a class or interface
  m2(options: {a: string, b: keyof this}) { 
    ...
  }
}

有没有办法解决?谢谢。

4

1 回答 1

1

是的,您可以提取类型并作为泛型参数options传递:this

type Options<T> = { a: string, b: keyof T };

class Foo {
    m2(options: Options<this>) {}
}

操场

于 2020-04-08T08:29:35.500 回答