M
M
Maxim Belousov2021-12-19 22:06:22
typescript
Maxim Belousov, 2021-12-19 22:06:22

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


Can you tell me how to read the next line?
function <T extends { new (...args: any[]): {} }>(constructor: T)


I read it like this:
{ new (...args: any[]): {} } is a class signature whose constructor takes an arbitrary number of arguments and returns an instance (object)

Accordingly, we are dealing with a function that takes a class constructor (constructor function) as an argument, this constructor must be of type T, i.e. be any arbitrary class.

If not, please correct.
I don't quite understand why the square brackets are here.

Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2021-12-20
@dedavarera

This function takes an argument constructorof 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 | undefinedand 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

A
Aetae, 2021-12-20
@Aetae

Everything is correct. Square brackets to indicate that args is an array, in the case of any, they can be omitted.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question