排除方法的打字稿键

时间:2020-04-17 12:53:18

标签: typescript

我想通过使用keyof功能和never来排除方法,但这不起作用:

class A {
  prop = 1;
  save() {}  
  hello() {}
}

type ExcludeFunctionPropertyNames<T> = {
  [K in keyof T]: T[K] extends Function ? never : T[K] 
};


function test<T>(param: T): ExcludeFunctionPropertyNames<T> {
  return { } as any;
}

test(new A()).prop; // I still see here `save` and `hello`

我的理解是never应该删除它们。

1 个答案:

答案 0 :(得分:1)

这里是您尝试做的一种解决方案:

class A {
  prop = 1;
  save() {}  
  hello() {}
}

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

function test<T>(param: T): ExcludeFunctionPropertyNames<T> {
  return { } as any;
}

test(new A()) // only prop available;

您在本文中有所有解释:https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c

相关问题