简体   繁体   中英

How do you declare function params in typescript with an interface?

I know in TS I can do:

const myFunc = (choice: string, index: number) => {}

but how would I use an interface in there (and should I in terms of best practice?)

I want to do something like

interface myFuncArgs {
  choice: string
  index: number
}
const myFunc = (choice, index): myFuncArgs  => {}

but it doesn't like that

I know for this simple case it doesn't really make sense but what if choice was a complex object and I wanted to declare the types of everything inside? it would look ugly inline.

how do I do this?

You can do what @YevgenGorbunkov said in comments:

const myFunc = ({choice, index}: myFuncArgs): void => {}

Or you can even do (if you don't like to pass an object):

type MyFunc = (choice : myFuncArgs['choice'], index: myFuncArgs['index']) => void

const myFunc : MyFunc = (choice, index) => {

}

Playground.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM