Skip to content

Commit f581e76

Browse files
committed
fix: 修复Class类型
1 parent 986f69b commit f581e76

File tree

2 files changed

+35
-9
lines changed

2 files changed

+35
-9
lines changed

docs/guide/types.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -774,7 +774,7 @@ type Funs = Overloads<typeof foo>;
774774

775775
**类型:**`Class<T = any>`
776776

777-
表示任意类的构造函数类型。可用于需要接受任意类作为参数的场景。
777+
表示任意类的构造函数类型,包括普通类和抽象类。可用于需要接受任意类作为参数的场景。
778778

779779
```typescript
780780
// 基本用法
@@ -799,6 +799,14 @@ createInstance(AClass); // ✅ Correct
799799
createInstance(BClass); // ❌ Error
800800
```
801801

802+
- `Class<T>` 可以接受泛型参数,用于限制类的构造参数类型。
803+
804+
### AbstractClass
805+
806+
**类型:**`AbstractClass<T = any>`
807+
808+
`Class`仅表示抽象类
809+
802810
### ImplementOf
803811

804812
**类型:**`ImplementOf<T>`

src/types/class.ts

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,31 @@
3131
* ```
3232
*/
3333

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>;
34+
export type ConcreteClass<T = object> = new (...args: any[]) => T;
35+
export type AbstractClass<T = object> = abstract new (...args: any[]) => T;
36+
export type Class<T = object> = ConcreteClass<T> | AbstractClass<T>;
3737

38-
// function test(cls: Class) {}
39-
// abstract class A {}
40-
// class B {}
38+
// abstract class A {
39+
// abstract methodA(): void;
40+
// }
4141

42-
// test(A);
43-
// test(B);
42+
// class B {
43+
// methodB() {
44+
// return "B";
45+
// }
46+
// }
47+
48+
// class B1 extends B {
49+
// methodB1() {
50+
// return "B1";
51+
// }
52+
// }
53+
54+
// // 正确的泛型约束方式
55+
// function test2<T extends B>(cls: Class<T>): void {
56+
// // 现在 cls 必须返回 T 类型,而 T 必须是 B 或其子类
57+
// }
58+
59+
// test2(B); // ✅ 正确
60+
// test2(B1); // ✅ 正确 - B1 是 B 的子类
61+
// test2(A); // ❌ 错误 - A 不是 B 的子类

0 commit comments

Comments
 (0)