Created
April 8, 2023 09:07
-
-
Save terasakisatoshi/cad4f623093777e98e389f0c629a4b87 to your computer and use it in GitHub Desktop.
ChatGPT knows TypeScript more than I do.
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
// sample.ts | |
function add(a: number, b: number): number { | |
return a + b; | |
} | |
console.log(add(1, 2)); |
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
```console | |
$ npm install -g ts-node | |
$ ts-node reverse.ts | |
[ 5, 4, 3, 2, 1 ] | |
[ 'e', 'd', 'c', 'b', 'a' ] | |
[ 5, 4, 3, 2, 1 ] | |
[ 'e', 'd', 'c', 'b', 'a' ] | |
``` |
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
class Point { | |
constructor(public x: number, public y: number) {} | |
distanceTo(other: Point): number { | |
const dx = this.x = other.x; | |
const dy = this.y = other.y; | |
return Math.sqrt(dx * dx + dy * dy); | |
} | |
} | |
const p1 = new Point(0, 0); | |
const p2 = new Point(3, 4); | |
console.log(p1.distanceTo(p2)); // => 5 |
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
/** | |
* Reverses the elements of an array. | |
* @param arr - The array to be reversed. | |
* @returns A new array containing the reversed elements. | |
*/ | |
function reverse<T>(arr: T[]): T[] { | |
const reversed: T[] = []; | |
for (let i = arr.length - 1; i >= 0; i--) { | |
reversed.push!(arr[i]); | |
} | |
return reversed; | |
} | |
// Example usage | |
const arr1 = [1, 2, 3, 4, 5]; | |
const arr2 = ["a", "b", "c", "d", "e"]; | |
// Call the reverse function without specifying the type parameter | |
console.log(reverse(arr1)); // => [5, 4, 3, 2, 1] | |
console.log(reverse(arr2)); // => ["e", "d", "c", "b", "a"] | |
// Call the reverse function with the type parameter specified | |
console.log(reverse<number>(arr1)); // => [5, 4, 3, 2, 1] | |
console.log(reverse<string>(arr2)); // => ["e", "d", "c", "b", "a"] |
Author
terasakisatoshi
commented
Apr 8, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment