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. 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.
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.