-
-
Save cem2ran/b1774b6406f29ab2efd98fa9cc329085 to your computer and use it in GitHub Desktop.
Revisions
-
cem2ran revised this gist
Apr 16, 2020 . 1 changed file with 2 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,2 @@ // No TypeScript, but statically typed let add = (a, b) => a + b; -
davidkpiano revised this gist
Apr 15, 2020 . 1 changed file with 54 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -4,6 +4,59 @@ function add(a, b) { } // Type function arguments // vvvvvv vvvvvv function add(a: number, b: number) { return a + b; } // Type return statement // vvvvvv function add(a: number, b: number): number { return a + b; } // Accept number or string // vvvvvvvvvvvvvvv vvvvvvvvvvvvvvv vvvvvvvvvvvvvvv function add(a: number | string, b: number | string): number | string { return a + b; } // That's a bit silly... // a and b should both be numbers or strings, don't mix! // Introduce a generic type T that represents number or string // // This will effectively result in: // (a: number, b: number): number // OR // (a: string, b: string): string // vvvvvvvvvvvvvvvvvvvvvvvvv function add<T extends number | string>(a: T, b: T): T { return a + b; } // Think of generic types (<T, Foo, Whatever>) as type variables! // Return an object with the result // vvvvvvvvvvvvv function add<T extends number | string>(a: T, b: T): { result: T } { return { result: a + b }; } // Make that type "reusable" // Notice how we're passing that generic type into the interface interface ResultObject<T> { result: T; } // vvvvvvvvvvvvvvv function add<T extends number | string>(a: T, b: T): ResultObject<T> { // The interface ensures that what we return fits the // ResultObject<T> interface return { result: a + b }; } // Now you know enough to be dangerous ☢️ -
davidkpiano created this gist
Apr 15, 2020 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,9 @@ // No TypeScript function add(a, b) { return a + b; } // Type function arguments function add(a: number, b: number) { return a + b; }