如何从打字稿中的类中创建不包括实例方法的类型? [英] How to create a type excluding instance methods from a class in typescript?

查看:19
本文介绍了如何从打字稿中的类中创建不包括实例方法的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given a class, containing both properties and methods, I'd like to derive a type that just contains its properties.

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

For example, if I define a class as follow:

class MyObject {

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

  instanceMethod() { ... }
}

我想要一个类型,比如 MyObjectConstructor,它会是这样的:

I'd like to have a type, say MyObjectConstructor that would be like this:

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

我知道我可以使用内置类型 Pick 并按名称手动选择我想要的键,但我不想必须一遍又一遍地重复键,并且必须更改每次我向班级添加新属性时都会使用它们.

I know I can use the built-in type Pick and manually select the keys I want by name, but I don't want to have to repeat the keys all over, and have to change them every time I add new properties to my class.

有没有办法定义一个泛型类型ConstructorType,它只在打字稿中返回一个类的属性?

Is there a way to define a generic type ConstructorType<T>that only returns the properties of a class in typescript ?

推荐答案

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

I've found a way to exclude all properties that match a given type, thanks to this article: https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c

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

I made a few adaptations, but here is the details:

// 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 并定义构造函数签名但没有结果.

There might be a simpler way, I've tried playing with ConstructorParameters and defining a constructor signature but without results.

更新

在此处浏览打字稿文档时发现了一个等价物:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types

Found an equivalent while browsing the typescript documentation here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types

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

由于省略的类型不是通用的,所以它不那么冗长,但它的想法是相同的.

It's a bit less verbose since the omitted type is not generic, but it's the same idea.

这篇关于如何从打字稿中的类中创建不包括实例方法的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆