Last active
March 10, 2022 05:17
-
-
Save kurtbrose/5785946717757e879489799e24b2bcd4 to your computer and use it in GitHub Desktop.
playing around with 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
// a First is a function which takes two arguments | |
// of any type, and returns the type of the first argument | |
type First<T, U> = (a: T, b: U) => T | |
// as a non-trivial example, add_timedelta(time, timedelta) returns time | |
// doubler is parameterized on <T, U>, passes those parameters through to First | |
// typescript can figure out that f(f(a, b), b) is type correct | |
// since f is of type First, then it will return the same type as its first argument | |
// note we don't have ANY concrete types yet | |
let doubler: <T, U>(f: First<T, U>, a: T, b: U) => T = (f, a, b) => f(f(a, b), b) | |
// f takes a string and a number, and returns a string e.g. ("a", 1) => "a1" | |
let f: (a: string, b: number) => string = (a, b) => a + b | |
// doubler knows NOTHING about F until this point | |
// at this callsite, doubler becomes a concrete type, T and U above becomes | |
// string and number | |
const result = doubler(f, "a", 1) | |
console.log(result) | |
// let's make the compiler work harder | |
// we will provide NO nominative types | |
// it needs to figure out that the lambda (a + b) | |
// will be passed "a" and 1, therefore it conforms | |
// to the shape of First we defined above | |
doubler((a, b) => a + b, "a", 1) | |
// let's make a negative test; a - b would be invalid | |
doubler((a, b) => +(a + b), "a", 1) | |
// "type number is not assignable to type string" | |
// "the expected type comes from the return type of this signature" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment