2

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?

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

0

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 };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.