Skip to content

Commit b46ced2

Browse files
committed
feat: type Class 现在支持匹配抽象类
1 parent 3bdb6c8 commit b46ced2

File tree

2 files changed

+27
-19
lines changed

2 files changed

+27
-19
lines changed

src/typecheck/inheritedOf.ts

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
import type { Class } from "../types"
1+
import type { Class } from "../types";
22

33
/**
44
* 判断cls是否继承自baseClass
55
* @param cls
66
* @param baseClass
77
* @returns {boolean}
88
*/
9-
export function inheritedOf(cls: Class, baseClass:Class):boolean {
10-
if(cls===undefined) return false
11-
if(cls===baseClass) return true
12-
if(!("__proto__" in cls)) return false
13-
let parent:any = (cls as any).__proto__
14-
while(parent!=null){
15-
if(parent===baseClass || parent.name===baseClass.name){
16-
return true
17-
}
18-
parent = parent.__proto__
9+
export function inheritedOf(cls: Class, baseClass: Class): boolean {
10+
if (cls === undefined) return false;
11+
if (cls === baseClass) return true;
12+
if (!("__proto__" in cls)) return false;
13+
let parent: any = (cls as any).__proto__;
14+
while (parent != null) {
15+
if (parent === baseClass || parent.name === baseClass.name) {
16+
return true;
1917
}
20-
return false
18+
parent = parent.__proto__;
19+
}
20+
return false;
2121
}

src/types/class.ts

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/**
22
* 表示任意类的构造函数类型。可用于需要接受任意类作为参数的场景。
3-
*
3+
*
44
* @example
55
* ```typescript
66
* // 基本用法
@@ -10,26 +10,34 @@
1010
* }
1111
* name: string;
1212
* }
13-
*
13+
*
1414
* // 函数接受任意类作为参数
1515
* function createInstance(ClassType: Class) {
1616
* return new ClassType();
1717
* }
18-
*
18+
*
1919
* // 用于类型约束
2020
* interface ClassDecorator {
2121
* (target: Class): void;
2222
* }
23-
*
23+
*
2424
* // 用于泛型约束
2525
* function getInstance<T extends Class>(ClassType: T): InstanceType<T> {
2626
* return new ClassType();
2727
* }
28-
*
28+
*
2929
* // 实际使用示例
3030
* const myInstance = getInstance(MyClass); // MyClass 的实例
3131
* ```
3232
*/
33-
export type Class<T = any> = new (...args: any[]) => T;
3433

35-
34+
export type ConcreteClass<T = any> = new (...args: any[]) => T;
35+
export type AbstractClass<T = any> = abstract new (...args: any[]) => T;
36+
export type Class<T = any> = ConcreteClass<T> | AbstractClass<T>;
37+
38+
// function test(cls: Class) {}
39+
// abstract class A {}
40+
// class B {}
41+
42+
// test(A);
43+
// test(B);

0 commit comments

Comments
 (0)