【问题标题】:Contional type to filter methods of object/class in TypeScript在 TypeScript 中过滤对象/类方法的条件类型
【发布时间】:2020-07-03 11:12:43
【问题描述】:

如何过滤对象的属性以仅获取那些是方法的?

const obj = {
  a: 1,
  b: 'text',
  c: () => null,
  d: (arg0: number) => arg0 + 1
}

type AllKeys = keyof typeof obj  // 'a' | 'b' | 'c' | 'd'

// type OnlyMethodsKeys = (???)  // 'c' | 'd'

【问题讨论】:

    标签: typescript types conditional-types


    【解决方案1】:

    来自https://github.com/microsoft/TypeScript/pull/21316

    type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T];
    type FunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>;
    
    type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
    type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
    

    所以我们可以这样做:

    type OnlyMethodsKeys = FunctionPropertyNames<typeof obj>  // 'c' | 'd'
    

    也适用于课程:

    class C {
      a = 1
      b = 'text'
      c() {
        return null
      }
      d(arg0: number) {
        return arg0 + 1
      }
    }
    
    type AllKeys = keyof C  // 'a' | 'b' | 'c' | 'd'
    
    type OnlyMethodsKeys = FunctionPropertyNames<C>  // 'c' | 'd'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 2020-03-29
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多