marcodali
marcodali

Reputation: 33

Why typescript does not have "function" type?

I'm a typescript beginner and I'm wonderig why I can't do this:

const obj: {
  property1: string
  property2: boolean
  property3: function
}

I think the only alternative is by doing:

const obj: {
  property1: string
  property2: boolean
  property3: any
}

Why I must implement the function on property3 inmediately on the object declaration?

Upvotes: 2

Views: 195

Answers (2)

user13258211
user13258211

Reputation:

The property must be implemented because it is part of the type of obj

If you do not want to initialize the property on declaration it must be made optional.

For example:

const obj: {
  property1: string
  property2: boolean
  property3?: any
}

Now you can do:

obj = { property1: 'A string'. property2: true };

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249536

Typescript does have a Function type, meaning a function that takes arguments any and returns a result of any, although I would highly recommend you not use it.

Instead you should use a function signature that allows you to specify the parameter types and the return type explicitly :

let obj: {
  property1: string
  property2: boolean
  property3: (a: string, b: boolean) => number
}

Playground Link

Upvotes: 6

Related Questions