devmeetings-react-ts-fork
Search…
devmeetings-react-ts-fork
Devmeeting React + Typescript
Speed dating
Typescript
It's just JavaScript
Basic types
Typing objects
Typing functions
Modules
Generics
Tasks
Hello React
Components & Props
Stateful components
Side-effects and context
What's next
Powered By
GitBook
Typing functions
When declaring a function we can type both the arguments and the return value:
1
function
multiply
(
a
:
number
,
b
:
number
)
:
number
{
2
return
a
*
b
;
3
}
Copied!
Reusable function type
Let's say the above function implements a very common pattern in out app: do some calculation with two numbers.
1
function
sum
(
a
:
number
,
b
:
number
)
:
number
{
2
return
a
+
b
;
3
}
4
5
function
modulo
(
a
:
number
,
b
:
number
)
:
number
{
6
return
a
%
b
;
7
}
Copied!
We can create a function type:
1
type
BinaryOperator
=
(
a
:
number
,
b
:
number
)
=>
number
;
2
const
subtract
:
BinaryOperator
=
(
a
,
b
)
=>
a
-
b
;
Copied!
The
void
type
One type is particularly useful with functions is
void
: to signify that nothing will be returned from the function:
1
function log(message): void {
2
console.log(message);
3
}
Copied!
Optional and default arguments
Function arguments can be marked as optional using the
?
sign
1
function
done
(
error
?:
Error
)
:
void
{
2
/* ... */
3
}
Copied!
We can also provide a default value; any argument with a default value will automatically be marked as optional.
1
function
complete
(
success
:
boolean
=
true
)
:
void
{
2
/* ... */
3
}
Copied!
Resources
Handbook: Functions
Previous
Typing objects
Next
Modules
Last modified
2yr ago
Copy link
Contents
Reusable function type
The void type
Optional and default arguments
Resources