首页 > 解决方案 > 排除方法的打字稿键

问题描述

我想通过使用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应该删除它们。

标签: typescript

解决方案


这是一个解决方案来做你正在尝试的事情:

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


推荐阅读