Skip to content
This repository was archived by the owner on Oct 12, 2022. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions js-and-ts/README.md
Original file line number Diff line number Diff line change
@@ -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`
```
13 changes: 13 additions & 0 deletions js-and-ts/format.js
Original file line number Diff line number Diff line change
@@ -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 };

46 changes: 46 additions & 0 deletions js-and-ts/robot.ts
Original file line number Diff line number Diff line change
@@ -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();
11 changes: 11 additions & 0 deletions js-and-ts/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"outDir": "./built",
"sourceMap": true,
"allowJs": true,
"target": "es6"
},
"include": [
"./**/*"
]
}