Answer the question
In order to leave comments, you need to log in
How to read generics in TypeScript?
Hello!
There is the following code:
function loggingClassDecorator(url: string) {
return function <T extends { new (...args: any[]): {} }>(constructor: T) {
return class extends constructor {
isUrgent: boolean = false
constructor(...args: any[]) {
super(...args)
console.log('Log: new instance of class ' + constructor.name)
console.log('Reporting URL: ' + url)
}
}
}
}
@loggingClassDecorator('https://example.com/needs-dark-mode')
class BugReport {
type: string = 'report'
constructor(public title: string) {}
}
const bug = new BugReport('Needs dark mode')
console.log(bug.title) // Needs dark mode
console.log(bug.type) // report
function <T extends { new (...args: any[]): {} }>(constructor: T)
Answer the question
In order to leave comments, you need to log in
This function takes an argument constructor
of any type T
, which is a subtype of the type { new (...args: any[]): {} }
In turn { new (...args: any[]): {} }
, this is absolutely the same as new (...args: any[]) => {}
. This is the signature of a constructor, with any number of any elements, and instantiating a value of type {}
.
Well, the type {}
is the set of all non-null values (not only objects), that is, in fact, it is like the any type, but without null | undefined
and with not broken variance . Here it can be painlessly replaced by type unknown
, in contrast to the same arguments, where, due to the contravariance of function arguments (and constructors), predicates on types break down and it’s normal not to do without any.
In general, absolutely any constructor is suitable for such a generic
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question