Skip to content

Instantly share code, notes, and snippets.

@terasakisatoshi
Created April 8, 2023 09:07
Show Gist options
  • Save terasakisatoshi/cad4f623093777e98e389f0c629a4b87 to your computer and use it in GitHub Desktop.
Save terasakisatoshi/cad4f623093777e98e389f0c629a4b87 to your computer and use it in GitHub Desktop.
ChatGPT knows TypeScript more than I do.
// sample.ts
function add(a: number, b: number): number {
return a + b;
}
console.log(add(1, 2));
```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' ]
```
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
/**
* 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"]
@terasakisatoshi
Copy link
Author

$ 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' ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment