I have a customized class called Collection
, which takes another class as a parameter named personClass
.
I expect the method add
to accept parameters that are used in the constructor of the class User
class Person {
constructor(public data: object) {
}
}
type GetConstructorParams<T> = T extends {
new (...params: infer Args): any
} ? Args : never
type GetConstructor<Instance> = new (...params: GetConstructorParams<Instance>) => Instance
class Collection<
Instance extends Person
> {
personClass: GetConstructor<Instance>
items: Instance[] = []
constructor(personClass: GetConstructor<Instance>) {
this.personClass = personClass
}
add(...params: GetConstructorParams<Instance>) {
const instance = new this.personClass(...params)
this.items.push(
instance
)
}
}
class User extends Person {
data: {
name: string
}
constructor(name: string) {
super({name})
}
get name() {
return this.data.name
}
}
const collection = new Collection(User)
collection.add('123')
^^^ TS2345: Argument of type 'string' is not assignable to parameter of type 'never'.
Next, I will attempt to make personClass an optional parameter. By default, personClass should be set to Person
How can I prevent errors in the collection.add('123')
method?