1

TS blows up with an error:

Error:(8, 20) TS7031: Binding element 'on' implicitly has an 'any' type.

Error:(8, 24) TS7031: Binding element 'children' implicitly has an 'any' type.

I have following function. I pass it two arguments.

// 
function On({on, children}) {
  return (
    <div>{on} {children}</div>
  )
}

How do I specify types for arguments in such a case? This syntax does not work:

function On({(on as boolean), (children as HTMLElement[])}) {
function On({(on: boolean), (children: HTMLElement[])}) {
function On({on: boolean, children: HTMLElement[]}) {
  return (
    <div>{on} {children}</div>
  )
}
2
  • 2
    The answers are correct; you need to do { on, children }: {on: boolean, children: HTMLElement[] }. There is a suggestion to allow type annotations inside binding patterns so if you want to see this you might want to go there and give it a 👍. Commented Jul 15, 2019 at 14:15
  • 1
    As a side note, you don't pass it 2 arguments, you pass it 1 argument, that is an object with 2 properties Commented Jul 15, 2019 at 14:53

2 Answers 2

3

Like this:

function On({on, children} : {on: boolean, children: HTMLElement[] }) {
    // your code
}

If you have a type/interface for the entire object you could also use that to make your code more readable:

interface OnOptions {
    on: boolean;
    children: HTMLElement[];
    someOtherProp: string;
}

function On({on, children} : OnOptions) {
    // your code
}
Sign up to request clarification or add additional context in comments.

Comments

1

See the section about Function declarations

type myType = { on: boolean, children: HTMLElement[]}
function On({on, children} : myType ) {
    // your code
}

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.