'How to set class param default value in case this value is another class
I have class Collection which excepts personClass as param. How to set default value Person to personClass parameter?
class Person {
constructor(public data: object) {
}
}
class Collection<A extends unknown[], T extends Person>{
personClass: new (...args: A) => T;
items: T[] = []
constructor(personClass: new (...args: A) => T = Person) {
^^^
TS2322: Type 'typeof Person' is not assignable to type 'new (...args: A) => T'. Types of construct signatures are incompatible.
this.personClass = personClass
}
add(...params: A) {
const person = new this.personClass(...params)
this.items.push(person)
}
}
class User extends Person {
data: {
name: string
}
constructor(name: string) {
super({ name })
}
get name() {
return this.data.name
}
}
const collection = new Collection(User)
const anotherCollection = new Collection()
collection.add('1') // correct
collection.add(1) // show error as expected
collection.add({name: '123'}) // show error as expected
anotherCollection.add({
name: '123',
age: 1
}) // expected
anotherCollection.add('1') // expected error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
