X
X
xelilok2862020-08-19 10:59:43
typescript
xelilok286, 2020-08-19 10:59:43

What is the best way to type the parameters of a function?

How best to type the parameters of a function, for example, through an interface or type, an example is needed. Yes, I understand that in the case with undefinedit will be NaN, but I'm interested in the typing of function parameters so that there are no such clutter asa: number | undefined, b: number | undefined

function sum (a: number | undefined, b: number | undefined) {
  return a + b
}

sum(1,3)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twoone, 2020-08-19
@xelilok286

If we omit the fact that the parameters of the addition function must be defined as mandatory, then the specific type undefinedcan be replaced with an optional modifier ?.
function а (a?: number, b?: number) {}
Otherwise, the parameters of the declaration function cannot be described. Another thing is a functional expression that can be described using a type.
For alias
type Sum = (a?: number, b?: number) => number;
For interface

interface ISum { (a?: number, b?: number): number; }

and use
const sum: Sum = (a, b) => a + b;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question