给定一个包含属性和方法的类,我想派生一个仅包含其属性的类型。
例如,如果我定义一个类如下:
class MyObject {
constructor(public prop1: string, public prop2: number) {}
instanceMethod() { ... }
}
我想要一个类型,说MyObjectConstructor
像这样:
type MyObjectConstructor = {
prop1: string;
prop2: string;
}
我知道我可以使用内置类型Pick
并按名称手动选择想要的键,但是我不想重复所有的键,而不必在每次向类添加新属性时都进行更改。
有没有一种方法可以定义ConstructorType<T>
只返回打字稿中类属性的泛型?
感谢本文,我找到了一种排除与给定类型匹配的所有属性的方法: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] 删除。
我来说两句