gpt4 book ai didi

typescript - 有没有办法在 TypeScript 中正确输入?

转载 作者:行者123 更新时间:2023-12-04 17:07:57 29 4
gpt4 key购买 nike

我想在 typescript 中输入这样的函数:

(anyClass, somePropertiesObject) => newClassExtendingAnyClassWithPropsAddedFromTheObject

该函数的目的非常简单,只需将一些类和一些对象作为参数并返回扩展提供的类的新类,但从第二个参数添加属性。

我真的很难弄清楚如何正确输入它。非常感谢您的帮助。

最佳答案

考虑这个例子:

type AnyClass = new (...args: any[]) => any

const extend = <
Class extends AnyClass, Obj extends Record<string, unknown>
>(AnyClass: Class, somePropertiesObject: Obj) => class _ extends AnyClass {
props = somePropertiesObject

constructor(...args: any[]) {
super(args)
}

}

class Derived {
name = 'Derived'
}
const obj = {
age: 42
}

const Result = extend(Derived, obj);

const test = new Result()

test.name // string
test.props.age // number

AnyClass - 表示任何构造函数的类型。我的意思是任何可以用 new 关键字调用的函数。我在 extend 函数中使用了这个约束,因为您希望第一个参数是一个类。

Obj - 表示具有 string 键和 unknown 值的任何对象。对应于第二个参数。

我在新类中使用了 props 属性来存储 somePropertiesObject

您可能已经注意到,所提供的类和对象的所有属性都可以在结果中使用。

关于typescript - 有没有办法在 TypeScript 中正确输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70120407/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com