繁体   English   中英

你如何在带有接口的打字稿中声明函数参数?

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

我知道在 TS 我可以做到:

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

但是我将如何使用那里的接口(我应该如何使用最佳实践?)

我想做类似的事情

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

但它不喜欢那样

我知道对于这个简单的案例,它并没有真正的意义,但是如果choice是一个复杂的对象并且我想声明其中所有内容的类型怎么办? 它会看起来丑陋的内联。

我该怎么做呢?

你可以按照@YevgenGorbunkov 在评论中所说的去做:

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

或者你甚至可以这样做(如果你不喜欢传递一个对象):

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

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

}

操场。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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