首页 > 解决方案 > 选项参数中的 keyof

问题描述

在方法类型签名中,类型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}) { 
    ...
  }
}

有没有办法解决?谢谢。

标签: typescript

解决方案


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

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

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

操场


推荐阅读