diff --git a/js-and-ts/README.md b/js-and-ts/README.md new file mode 100644 index 0000000..2b3ecfb --- /dev/null +++ b/js-and-ts/README.md @@ -0,0 +1,17 @@ +# TypeScript Sample: Mixing TypeScript and JavaScript + +## Overview + +A sample of how to use the `allowJS` option to use both JavaScript and TypeScript together. +A simple text formatter is provided, written in JavaScript. This formatter is then used +within a TypeScript class to format a computation. + +To run this sample, you must have `node` installed. You can also use `ts-node` to run this directly +without a compilation from TypeScript to JavaScript. + +## Running + +```bash +$ tsc robot.ts` +$ node robot.js` +``` \ No newline at end of file diff --git a/js-and-ts/format.js b/js-and-ts/format.js new file mode 100644 index 0000000..9b6ebd7 --- /dev/null +++ b/js-and-ts/format.js @@ -0,0 +1,13 @@ +const surroundWithStars = (value) => { + const valueLength = value.toString().length; + const topBottomBorder = '*'.repeat(valueLength + 2); + + return topBottomBorder + + "\n" + + '*' + value.toString() + '*' + + "\n" + + topBottomBorder; +} + +module.exports.Formatter = { surroundWithStars }; + diff --git a/js-and-ts/robot.ts b/js-and-ts/robot.ts new file mode 100644 index 0000000..0542c12 --- /dev/null +++ b/js-and-ts/robot.ts @@ -0,0 +1,46 @@ +// This import wouldn't be possible without the allowJS option in tsconfig +import { Formatter } from './format.js'; + +interface Robot { + name: String; + currentComputation: Number; +} + +class Robot { + constructor(public name: String) { + this.name = name; + this.currentComputation = 0; + } + + // Given a mathematical operation, return a value based on the value passed, + // the operation and the number 10 + compute(operation, value) { + let computedValue = 0; + switch(operation) { + case '+': + computedValue = value + 10; + break; + case '-': + computedValue = value - 10; + break; + case '/': + computedValue = value / 10; + break; + case '*': + computedValue = value * 10; + break; + default: + console.log("Does not compute!!") + } + this.currentComputation = computedValue; + } + + // Using an external JS module, format the computed value from our robot + displayCurrentComputation() { + console.log(Formatter.surroundWithStars(this.currentComputation)); + } +} + +const hal = new Robot('Hal'); +hal.compute('+', 32); +hal.displayCurrentComputation(); \ No newline at end of file diff --git a/js-and-ts/tsconfig.json b/js-and-ts/tsconfig.json new file mode 100644 index 0000000..2a9bebf --- /dev/null +++ b/js-and-ts/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "outDir": "./built", + "sourceMap": true, + "allowJs": true, + "target": "es6" + }, + "include": [ + "./**/*" + ] +} \ No newline at end of file