简体   繁体   English

将函数参数定义为 Typescript 中的对象

[英]Define function arguments as object in Typescript

Rather than calling functions where the arguments are passed individually, I prefer to pass them as an object so that the order is not important.与其调用单独传递参数的函数,我更喜欢将它们作为对象传递,这样顺序就不重要了。

eg例如

const sum = ({ arg1, arg2, arg3 }) => arg1 + arg2 + arg3;

Now I'm migrating some code that I have across, to Typescript and I am unsure how I am supposed to define the interface for such a function.现在我正在将我拥有的一些代码迁移到 Typescript,但我不确定我应该如何为这样的函数定义接口。

I've tried something like this and it doesn't work:我试过这样的事情,但它不起作用:

在此处输入图片说明

Any clues?有什么线索吗?

How about:怎么样:

interface InputObj {
    arg1: number;
    arg2: number;
    arg3: number;
}

interface ExampleProps {
    sum: (input: InputObj) => number
}

Or inline:或内联:

interface ExampleProps {
  sum: (
    input: {
      arg1: number;
      arg2: number;
      arg3: number;
    }
  ) => number;
}

But depending on your use case you may not need to define ExampleProps .但是根据您的用例,您可能不需要定义ExampleProps Here is your sum function without the arbitrary input object name:这是没有任意input对象名称的sum函数:

const sum = ({
  arg1,
  arg2,
  arg3
}: {
  arg1: number;
  arg2: number;
  arg3: number;
}) => arg1 + arg2 + arg3;

Here is a fully annotated example as function expression:这是一个完整注释的示例作为函数表达式:

const sum: ({ 
  arg1, 
  arg2,
  arg3 
}: {
  arg1: number;
  arg2: number;
  arg3: number;
}) => number = ({ arg1, arg2, arg3 }) => arg1 + arg2 + arg3;

Here is another and better alternative for arrow functions.这是箭头函数的另一个更好的替代方案。 Only arguments are annotated and compiler can infer return type correctly.只有参数被注释,编译器可以正确推断返回类型。 Function has less clutter and works just as before.功能没有那么杂乱,并且像以前一样工作。

const sum = ({ 
  arg1,
  arg2,
  arg3
}: {
  arg1: number;
  arg2: number;
  arg3: number;
}) => arg1 + arg2 + arg3;

If you are going to annotate your function in a seperate file:如果您要在单独的文件中注释您的函数:

interface Args {
  arg1: number;
  arg2: number;
  arg3: number;
}

type Sum = (input: Args) => number;
const sum: Sum = ({ arg1, arg2, arg3 }) => arg1 + arg2 + arg3;

You can use any as argument type if argument types are not known.如果参数类型未知,您可以使用any作为参数类型。 Return type will be inferred as any:返回类型将被推断为任何:

const sum = ({ 
  arg1,
  arg2,
  arg3
}: any) => arg1 + arg2 + arg3;

So this one is equivalent to previous example:所以这个相当于前面的例子:

const sum: ({ arg1, arg2, arg3 }: any) => any

This may not make that much sense for arrow functions but you can set types for known arguments and use key-value pairs for annotating addititional argumens:这对于箭头函数可能没有多大意义,但您可以为已知参数设置类型并使用键值对来注释附加参数:

const sum = ({ 
  arg1,
  arg2,
  arg3
}: {
  arg1: number;
  arg2: number;
  arg3: number;
  [key: string]: number;
}) => arg1 + arg2 + arg3;

You can also use generics:您还可以使用泛型:

interface Args {
  arg1: number;
  arg2: number;
  arg3: number;
}

const sum = <T extends Args>({ 
  arg1,
  arg2,
  arg3
}: T) => arg1 + arg2 + arg3;

Here is same examples, sum as function statement.这是相同的示例, sum 作为函数语句。

function sum({
  arg1,
  arg2,
  arg3
}: {
  arg1: number;
  arg2: number;
  arg3: number;
}): number {
  return arg1 + arg2 + arg3;
}

If you have complicated implementation detail in your function's body, function statement can be better choice for its ergonomics.如果您的函数体中有复杂的实现细节,则函数语句可能是其人体工程学的更好选择。 Plus generics looks less clumsy on function statements.加上泛型在函数语句上看起来不那么笨拙。

If you need to explicitly annotate a function type you can go with:如果您需要显式注释函数类型,您可以使用:

type Foo = (object: { arg1: number, arg2: number; arg3: number }) => number;

const bar: Foo = ({arg1, arg2, arg3}) =>  arg1 + arg2 + arg3 

To play around with type annotations and share results I advise TypeScript Playground <= check there above :)要使用类型注释并共享结果,我建议TypeScript Playground <= 检查上面的内容:)

Have not tried TypeScript.没有尝试过 TypeScript。 In JavaScript would also consider including default values for the properties of the object to avoid the error在 JavaScript 中还会考虑为对象的属性包含默认值以避免错误

Uncaught TypeError: Cannot destructure property `arg1` of 'undefined' or 'null'.

for为了

sum()

 const sum = ({ arg1, arg2, arg3 }) => arg1 + arg2 + arg3; try { console.log(sum()) } catch (e) { console.error(e) }

which can be avoided by setting each value to 0 where the expected parameters and return value is a JavaScript integer这可以通过将每个值设置为0来避免,其中预期参数和返回值是 JavaScript 整数

 const sum = ({ arg1 = 0, arg2 = 0, arg3 = 0 } = {}) => arg1 + arg2 + arg3; try { console.log(sum()) // 0 } catch (e) { console.error(e) }

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

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