如何从打字稿中的类中创建排除实例方法的类型?

HHK

给定一个包含属性和方法的类,我想派生一个仅包含其属性的类型。

例如,如果我定义一个类如下:

class MyObject {

  constructor(public prop1: string, public prop2: number) {}

  instanceMethod() { ... }
}

我想要一个类型,说MyObjectConstructor像这样:

type MyObjectConstructor = {
  prop1: string;
  prop2: string;
}

我知道我可以使用内置类型Pick并按名称手动选择想要的键,但是我不想重复所有的键,而不必在每次向类添加新属性时都进行更改。

有没有一种方法可以定义ConstructorType<T>只返回打字稿中类属性的泛型

HHK

感谢本文,我找到了一种排除与给定类型匹配的所有属性的方法:https : //medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c

我做了一些改编,但这是细节:

// 1 Transform the type to flag all the undesired keys as 'never'
type FlagExcludedType<Base, Type> = { [Key in keyof Base]: Base[Key] extends Type ? never : Key };

// 2 Get the keys that are not flagged as 'never'
type AllowedNames<Base, Type> = FlagExcludedType<Base, Type>[keyof Base];

// 3 Use this with a simple Pick to get the right interface, excluding the undesired type
type OmitType<Base, Type> = Pick<Base, AllowedNames<Base, Type>>;

// 4 Exclude the Function type to only get properties
type ConstructorType<T> = OmitType<T, Function>;

试试看

可能有一种更简单的方法,我尝试使用ConstructorParameters并定义了构造函数签名,但没有结果。

更新资料

在浏览打字稿文档时找到了等效项:https : //www.typescriptlang.org/v2/docs/handbook/advanced-types.html#example-1

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

因为省略的类型不是泛型的,所以它有点冗长,但这是相同的想法。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

从打字稿中的超类调用重写的方法

如何从打字稿中的实例方法访问静态成员?

从打字稿中的静态方法中检索类名称

如何从打字稿中的数组中提取类型?

从打字稿方法中获取方法名称

如何从打字稿中的类型中排除仅吸气剂的属性

如何在打字稿中排除方法的类中的所有属性的属性名称

在打字稿中创建动态类实例

如何从打字稿中带标签的联合类型中提取类型?

如何从打字稿中的字符串中获取一种枚举类型?

如何从打字稿中的依赖项正确要求类型?

如何从打字稿中预定义的基类中删除动态键?

如何从打字稿中的扩展功能返回此自类型

如何从打字稿中获取http响应

如何从打字稿中的JSON中提取特定值

从打字稿中具有相同父类的其他实例访问受保护的方法

如何使用React从打字稿中的对象创建HTML元素

从打字稿中的扩展类返回通用值

如何从打字稿中的类中提取类型?

如何从打字稿中的数组类型获取类型的索引号?

如何使用AMD模块在普通js中创建打字稿类的对象实例

如何从打字稿中的动态键数组推断类型化数组?

如何从打字稿中的类数组中解开类型

使用类的方法在打字稿中创建联合类型

如何从打字稿中的typeof对象中删除索引

无法从打字稿中的异步方法发出事件

如何从打字稿中嵌套对象的属性中获取类型

从打字稿中的数组变量对象创建记录

如何从打字稿中的对象文字声明类型?