Skip to content

Commit

Permalink
tutorial/typeScriptFeatures.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
voltrevo committed Jul 7, 2023
1 parent 4c90c5d commit 8e5f41c
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 4 deletions.
4 changes: 2 additions & 2 deletions inputs/passing/enum.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! test_output(10)

import Numbers from "./helpers/Numbers.ts";
import Num from "./helpers/Num.ts";

export default function () {
return Numbers.One + Numbers.Two + Numbers.Three + Numbers.Four;
return Num.One + Num.Two + Num.Three + Num.Four;
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
enum Numbers {
enum Num {
Zero,
One,
Two,
Three,
Four,
}

export default Numbers;
export default Num;
1 change: 1 addition & 0 deletions website/src/playground/files/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const orderedFiles = [
"/tutorial/structuralComparison.ts",
"/tutorial/binaryTree.ts",
"/tutorial/specialFunctions.ts",
"/tutorial/typeScriptFeatures.ts",
"/tutorial/treeShaking.ts",
];

Expand Down
75 changes: 75 additions & 0 deletions website/src/playground/files/root/tutorial/typeScriptFeatures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Sometimes TypeScript features generate code. ValueScript supports that too.

export default function () {
const bigFruit = biggerFruit(Fruit.Lemon, Fruit.Mango);
const point = new Point(3, 4);

return {
bigFruit: {
raw: bigFruit,
display: Fruit[bigFruit],
note: isCitrus(bigFruit) ? "citrus" : "not citrus",
},
pointDist: point.dist(),
};
}

// Enums don't exist in JavaScript
enum Fruit {
Apple,
Banana,
Orange,
Grape,
Mango,
Pineapple,
Watermelon,
Lemon,
}

class Point {
constructor(
// By specifying public here, these parameters are automatically initialized
// as fields
public x: number,
public y: number,
) {}

dist() {
return Math.sqrt(this.x ** 2 + this.y ** 2);
}
}

function biggerFruit(left: Fruit, right: Fruit): Fruit {
const order = [
Fruit.Grape,
Fruit.Lemon,
Fruit.Banana,
Fruit.Orange,
Fruit.Apple,
Fruit.Mango,
Fruit.Pineapple,
Fruit.Watermelon,
];

return order.indexOf(left) > order.indexOf(right) ? left : right;
}

function isCitrus(fruit: Fruit): boolean {
switch (fruit) {
case Fruit.Apple:
case Fruit.Banana:
case Fruit.Grape:
case Fruit.Mango:
case Fruit.Pineapple:
case Fruit.Watermelon:
return false;

case Fruit.Orange:
case Fruit.Lemon:
return true;
}

// TypeScript knows this is unreachable, so it doesn't complain that we're
// failing to return a boolean. If you comment out one of the cases, it'll
// emit an error.
}

0 comments on commit 8e5f41c

Please sign in to comment.