Last active
December 10, 2020 03:14
-
-
Save CMCDragonkai/eccabcbcc01fd946cad7b8f0deeec88d to your computer and use it in GitHub Desktop.
Function Type Signature Declarations in TypeScript #typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// there are several ways to declare function types | |
// these are "first-order" functions | |
// normal function declaration | |
function f1 (i: number): number { | |
return i + 1; | |
} | |
// this relies on inference | |
const f2 = (i: number) => i + 1; | |
const f3 = (i: number): number => i + 1; | |
// notice the name of the type parameter | |
// it does not need to match parameter name | |
// but by convention it does | |
const f4: (i: number) => number = (i) => i + 1; | |
// declaring higher order functions can be messy | |
// this is because of the need to give arbitrary names | |
// to the type parameters of the argument functions | |
function h1 (f: (i: number) => number): number { | |
return f(1); | |
} | |
const h2 = (f: (i: number) => number) => f(1); | |
const h3 = (f: (i: number) => number): number => f(1); | |
const h4: (f: (i: number) => number) => number = (f) => f(1); | |
// note that f4 and h4 is when the entire function type is being declared ahead of time | |
// so therefore you should make use of aliases when you can | |
type fAlias = (i: number) => number; | |
const h5 = (f: fAlias): number => f(1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment