Home > Blockchain >  In Typescript, how to define/type a function with additional properties
In Typescript, how to define/type a function with additional properties

Time:09-14

In javascript I can do something like this:

function hello() { console.log('Hello')}
hello.rating = "super useful"

So this hello function is now "special", since it has this additional property rating

How would one declare such a function in Typescript?

I know I could use typeof, but this is not what I want to use.

Here is a playground:

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABACwKYBt1wBQEpEDeAUIokQL5FqZwB0ATgIYxhSIC8iARAM4gAOqelyKioAT0GIAGh0QTBcYCgxZREBDzbiAXLM54OAPkLkgA

CodePudding user response:

You are looking for call signatures.

You can do something like this:

type UberFunctionObject = {
  rating: string
  (): void
}

The main idea is that you actually define a type for an object and then declare the type(s) of how that object could be called, as a function.

  • Related