typescript - TS 推断出我的泛型函数的未知返回类型,我该如何防止呢?以一般的方式?
问题描述
我知道标题听起来很混乱。我不知道如何用一句话来解释我的问题。但是这段代码解释了我的意思:
// This is the class that I want to extend further on.
class User {
public name: string
constructor(name: string) {
this.name = name
}
}
type Constructable<InstanceType> = {
new (...args: any[]): InstanceType
}
type MyFactory<InstanceType> = {
newWithRandomName(): InstanceType
}
type ExtendedClass<InstanceType, ClassType extends Constructable<InstanceType>> = ClassType & MyFactory<InstanceType>
// This is the function that I use to extend the class.
function extendClass<InstanceType, ClassType extends Constructable<InstanceType>>(
classType: ClassType
): ExtendedClass<InstanceType, ClassType> {
return new Proxy(classType, {
get(target, prop, receiver) {
if (prop === "newWithRandomName") {
return () => new classType("Joe Random")
}
return Reflect.get(target, prop, receiver)
}
}) as ExtendedClass<InstanceType, ClassType>
}
const ExtendedUser = extendClass(User)
// Both of these lines work as expected
let user1 = new User("John Doe")
let user2 = new ExtendedUser("Jane Doe")
// But this line returns an unknown type,
// even though I thought I clearly defined
// what type should be returned, didn't I?
let user3 = ExtendedUser.newWithRandomName()
console.log(user3.name)
解决方案
您不需要两个通用参数,请看下面:
// This is the class that I want to extend further on.
class User {
public name: string
constructor(name: string) {
this.name = name
}
}
type MyFactory<T> = {
newWithRandomName(): T
}
type ExtendedClass<T extends new (...args: any[]) => any> = T & MyFactory<T>
// This is the function that I use to extend the class.
function extendClass<ClassType extends new (...args: any[]) => any>(
classType: ClassType
): ExtendedClass<ClassType> {
return new Proxy(classType, {
get(target, prop, receiver) {
if (prop === 'newWithRandomName') {
return () => new classType('Joe Random')
}
return Reflect.get(target, prop, receiver)
}
}) as ExtendedClass<ClassType>
}
const ExtendedUser = extendClass(User)
// Both of these lines work as expected
const user1: User = new User('John Doe')
const user2: User = new ExtendedUser('Jane Doe')
// But this line returns an unknown type,
// even though I thought I clearly defined
// what type should be returned, didn't I?
const user3: User = ExtendedUser.newWithRandomName()
console.log(user3.name)
推荐阅读
- amazon-s3 - 为什么 LogDNA 仅将部分数据积压到 Amazon S3?
- amazon-web-services - Terraform ECS / Github Actions 似乎忽略了 ALB 健康检查
- android - 当我们将 Jetpack Navigation 与 FragmentContainerView 一起使用时,如何避免片段重新创建?
- css - 使用 CSS 样式表更改闪亮的“确定”按钮 (confirmButtonCol) 的颜色
- android - 如何让手机模拟器运行手机应用程序而不佩戴操作系统应用程序?
- python - 为什么我的 ChoiceField 没有从我的 Django 表单呈现到模板上?
- javascript - 如何在需要时替换 debounceTime(0) 发射?
- sql - 通过 Azure 流分析作业使用时间戳时未写入数据
- firebase - 未处理的异常:'package:flutter/src/widgets/navigator.dart':断言失败:'!navigator._debugLocked':不正确
- javascript - jQuery - 如何在下拉值更改时在 Kendo Grid 内的 Kendo DatePicker 上设置今天的日期