├── .editorconfig
├── .gitignore
├── .vscode
├── launch.json
└── settings.json
├── bs-config.json
├── examples
├── arrow-functions
│ ├── index.html
│ ├── plnkr.json
│ ├── scripts
│ │ └── arrow-functions.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── banking
│ ├── index.html
│ ├── plnkr.json
│ ├── scripts
│ │ ├── account.ts
│ │ ├── accountList.ts
│ │ ├── arrayType.ts
│ │ ├── bankingAccount.ts
│ │ ├── checkingAccount.ts
│ │ ├── constants.ts
│ │ ├── iAccount.ts
│ │ ├── list.ts
│ │ └── savingsAccount.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── basic-types
│ ├── index.html
│ ├── plnkr.json
│ ├── scripts
│ │ └── basicTypes.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── calculator-jquery
│ ├── index.html
│ ├── plnkr.json
│ ├── scripts
│ │ └── calculatorJQuery.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── calculator
│ ├── index.html
│ ├── plnkr.json
│ ├── scripts
│ │ └── calculator.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── class-extension
│ ├── index.html
│ ├── plnkr.json
│ └── scripts
│ │ └── classExtension.ts
├── classes
│ ├── index.html
│ ├── plnkr.json
│ └── scripts
│ │ └── definingClasses.ts
├── compounder
│ ├── index.html
│ ├── plnkr.json
│ ├── scripts
│ │ └── compounder.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── cookbook
│ ├── .vscode
│ │ └── settings.json
│ ├── package-lock.json
│ ├── package.json
│ ├── readme.md
│ ├── src
│ │ ├── images
│ │ │ └── cutlery.png
│ │ ├── index.html
│ │ ├── json
│ │ │ └── recipeTypes.json
│ │ ├── scripts
│ │ │ ├── baseRecipeCategory.ts
│ │ │ ├── bootstrapper.ts
│ │ │ ├── foodGroup.ts
│ │ │ ├── ingredient.ts
│ │ │ ├── interfaces.ts
│ │ │ ├── recipeCategories.ts
│ │ │ ├── recipeCategory.ts
│ │ │ ├── recipeCategorySummary.ts
│ │ │ ├── recipeExample.ts
│ │ │ ├── recipeLoader.ts
│ │ │ └── renderer.ts
│ │ └── styles
│ │ │ └── app.css
│ ├── superstatic.json
│ └── tsconfig.json
├── generics
│ ├── index.html
│ ├── plnkr.json
│ ├── scripts
│ │ └── generics.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── greeter
│ ├── index.html
│ ├── plnkr.json
│ ├── scripts
│ │ └── greeter.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── interfaces
│ ├── index.html
│ ├── plnkr.json
│ └── scripts
│ │ └── interfaces.ts
├── modules-barrels
│ ├── index.html
│ ├── scripts
│ │ ├── account
│ │ │ ├── accountList.ts
│ │ │ ├── bankingAccount.ts
│ │ │ ├── checkingAccount.ts
│ │ │ ├── iAccount.ts
│ │ │ ├── index.ts
│ │ │ └── savingsAccount.ts
│ │ ├── constants.ts
│ │ └── main.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── modules-simple
│ ├── index.html
│ ├── scripts
│ │ ├── bankingAccount.ts
│ │ ├── iAccount.ts
│ │ └── main.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── modules-starter
│ ├── index.html
│ ├── scripts
│ │ ├── conference.ts
│ │ ├── main.ts
│ │ └── speaker.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── modules
│ ├── index.html
│ ├── scripts
│ │ ├── accountList.ts
│ │ ├── arrayType.js.map
│ │ ├── bankingAccount.ts
│ │ ├── checkingAccount.ts
│ │ ├── constants.ts
│ │ ├── iAccount.ts
│ │ ├── main.ts
│ │ └── savingsAccount.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── object-oriented
│ ├── 1 - Course Overview
│ │ └── readme.md
│ ├── 2 - Introduction to Object-Oriented Programming in TypeScript
│ │ ├── .vscode
│ │ │ ├── launch.json
│ │ │ └── settings.json
│ │ ├── dist
│ │ │ └── bundle.js
│ │ ├── index.html
│ │ ├── package-lock.json
│ │ ├── package.json
│ │ ├── readme.md
│ │ ├── src
│ │ │ ├── main.js
│ │ │ ├── main.js.map
│ │ │ ├── main.ts
│ │ │ └── styles
│ │ │ │ └── styles.css
│ │ ├── tsconfig.json
│ │ └── webpack.config.js
│ ├── 3 - Classes and Objects
│ │ ├── .vscode
│ │ │ ├── launch.json
│ │ │ └── settings.json
│ │ ├── dist
│ │ │ └── bundle.js
│ │ ├── index.html
│ │ ├── package-lock.json
│ │ ├── package.json
│ │ ├── readme.md
│ │ ├── src
│ │ │ ├── main.js
│ │ │ ├── main.js.map
│ │ │ ├── main.ts
│ │ │ ├── scripts
│ │ │ │ ├── checking-account.ts
│ │ │ │ └── renderer.ts
│ │ │ └── styles
│ │ │ │ └── styles.css
│ │ ├── tsconfig.json
│ │ └── webpack.config.js
│ ├── 4 - Inheritance and Abstraction
│ │ ├── .vscode
│ │ │ ├── launch.json
│ │ │ └── settings.json
│ │ ├── dist
│ │ │ └── bundle.js
│ │ ├── index.html
│ │ ├── package-lock.json
│ │ ├── package.json
│ │ ├── readme.md
│ │ ├── src
│ │ │ ├── main.js
│ │ │ ├── main.js.map
│ │ │ ├── main.ts
│ │ │ ├── scripts
│ │ │ │ ├── account-list.ts
│ │ │ │ ├── bank-account.ts
│ │ │ │ ├── checking-account.ts
│ │ │ │ ├── enums.ts
│ │ │ │ ├── renderer.ts
│ │ │ │ └── savings-account.ts
│ │ │ └── styles
│ │ │ │ └── styles.css
│ │ ├── tsconfig.json
│ │ └── webpack.config.js
│ ├── 5 - Interfaces and Polymorphism
│ │ ├── .vscode
│ │ │ ├── launch.json
│ │ │ └── settings.json
│ │ ├── data.json
│ │ ├── dist
│ │ │ └── bundle.js
│ │ ├── index.html
│ │ ├── package-lock.json
│ │ ├── package.json
│ │ ├── readme.md
│ │ ├── src
│ │ │ ├── images
│ │ │ │ ├── acmebank.afphoto
│ │ │ │ ├── acmebank.jpg
│ │ │ │ ├── atm.jpg
│ │ │ │ ├── checking.jpg
│ │ │ │ └── savings.jpg
│ │ │ ├── main.js
│ │ │ ├── main.js.map
│ │ │ ├── main.ts
│ │ │ ├── scripts
│ │ │ │ ├── account-list.ts
│ │ │ │ ├── atm.ts
│ │ │ │ ├── bank-account.ts
│ │ │ │ ├── checking-account.ts
│ │ │ │ ├── constants.ts
│ │ │ │ ├── enums.ts
│ │ │ │ ├── interfaces.ts
│ │ │ │ ├── renderer.ts
│ │ │ │ └── savings-account.ts
│ │ │ └── styles
│ │ │ │ └── styles.css
│ │ ├── tsconfig.json
│ │ └── webpack.config.js
│ ├── 6 - Putting It All Together
│ │ └── readme.md
│ └── solution
│ │ ├── .vscode
│ │ ├── launch.json
│ │ └── settings.json
│ │ ├── data.json
│ │ ├── dist
│ │ └── bundle.js
│ │ ├── index.html
│ │ ├── package-lock.json
│ │ ├── package.json
│ │ ├── readme.md
│ │ ├── src
│ │ ├── images
│ │ │ ├── acmebank.afphoto
│ │ │ ├── acmebank.jpg
│ │ │ ├── atm.jpg
│ │ │ ├── checking.jpg
│ │ │ └── savings.jpg
│ │ ├── main.js
│ │ ├── main.js.map
│ │ ├── main.ts
│ │ ├── scripts
│ │ │ ├── account-list.ts
│ │ │ ├── atm.ts
│ │ │ ├── bank-account.ts
│ │ │ ├── checking-account.ts
│ │ │ ├── constants.ts
│ │ │ ├── enums.ts
│ │ │ ├── interfaces.ts
│ │ │ ├── renderer.ts
│ │ │ └── savings-account.ts
│ │ └── styles
│ │ │ └── styles.css
│ │ ├── tsconfig.json
│ │ └── webpack.config.js
├── optional-default-parameters
│ ├── index.html
│ ├── plnkr.json
│ ├── scripts
│ │ └── optionalDefaultRestParameters.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── parameter-types
│ ├── index.html
│ ├── plnkr.json
│ ├── scripts
│ │ └── parameterTypes.ts
│ └── styles
│ │ ├── app.css
│ │ └── bootstrap.min.css
├── scratchpad
│ ├── demo.js
│ ├── demo.js.map
│ └── demo.ts
└── unions-aliases-const-enums
│ ├── index.html
│ ├── plnkr.json
│ ├── scripts
│ ├── constEnums.ts
│ ├── typeAliases.ts
│ └── unionTypes.ts
│ └── styles
│ ├── app.css
│ └── bootstrap.min.css
├── index.html
├── package-lock.json
├── package.json
├── readme.md
└── tsconfig.json
/.editorconfig:
--------------------------------------------------------------------------------
1 | # http://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | end_of_line = lf
9 | insert_final_newline = true
10 | trim_trailing_whitespace = true
11 |
12 | # [*.md]
13 | # max_line_length = 0
14 | # trim_trailing_whitespace = false
15 |
16 | # Indentation override
17 | #[lib/**.js]
18 | #[{package.json,.travis.yml}]
19 | #[**/**.js]
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | examples/**/scripts/**/*.js.map
2 | examples/**/scripts/**/*.js
3 |
4 | !examples/cookbook/src/scripts/libs/jquery-1.12.2.js
5 |
6 | node_modules
7 | jspm_packages
8 | bower_components
9 |
10 | plnkr.html
11 | #plnkr.demo.html
12 |
13 | npm-debug.log
14 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "type": "chrome",
6 | "request": "launch",
7 | "name": "Launch Chrome against localhost",
8 | "url": "http://localhost:3000",
9 | "sourceMaps": true,
10 | "webRoot": "${workspaceRoot}"
11 | },
12 | {
13 | "type": "chrome",
14 | "request": "attach",
15 | "name": "Attach to Chrome",
16 | "port": 9222,
17 | "webRoot": "${workspaceRoot}"
18 | }
19 | ]
20 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | // Place your settings in this file to overwrite default and user settings.
2 | {
3 | "files.exclude": {
4 | "**/*.js": {
5 | "when": "$(basename).ts"
6 | },
7 | "**/*.js.map": {
8 | "when": "$(basename)"
9 | }
10 | // "examples/**/*.js.map": true,
11 | // "examples/**/*.js": true
12 | }
13 | }
--------------------------------------------------------------------------------
/bs-config.json:
--------------------------------------------------------------------------------
1 | {
2 | "server": {
3 | "baseDir": [
4 | "./"
5 | ]
6 | }
7 | }
--------------------------------------------------------------------------------
/examples/arrow-functions/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Using Lambdas
7 |
8 |
9 |
10 |
11 |
12 |
Using Arrow Functions
13 |
14 |
Start/Stop Timer
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/examples/arrow-functions/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Working with Lambdas",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/arrow-functions/scripts/arrow-functions.ts:
--------------------------------------------------------------------------------
1 | var Timer: any = function() {
2 | this.start = document.getElementById('startButton');
3 | this.stop = document.getElementById('stopButton');
4 | this.timer = document.getElementById('timer');
5 | this.timerId = null;
6 | this.value = 0;
7 |
8 | //With lambda (this will be correct)
9 | this.start.addEventListener('click',() => this.updateTimer());
10 |
11 | //Without lambda (this will be button which isn't correct)
12 | //this.start.addEventListener('click', this.updateTimer);
13 |
14 | this.stop.addEventListener('click', () => this.stopTimer());
15 | };
16 |
17 | //Using standard JavaScript prototype pattern here rather than TypeScript classes
18 | //(they haven't been covered yet)
19 |
20 | Timer.prototype = {
21 | updateTimer: function () {
22 | //Catch 'this' errors
23 | try {
24 | this.start.disabled = true;
25 | this.timerId = window.setInterval(() => this.timer.innerHTML = this.value++, 1000);
26 | }
27 | catch (exp) {
28 | alert(exp);
29 | }
30 | },
31 | stopTimer: function () {
32 | this.start.disabled = false;
33 | window.clearInterval(this.timerId);
34 | this.value = 0;
35 | this.timer.innerHTML = 0;
36 | }
37 | };
38 |
39 | var timer = new Timer();
40 |
41 |
--------------------------------------------------------------------------------
/examples/arrow-functions/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/banking/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Using TypeScript Classes
7 |
8 |
9 |
10 |
11 | Bank Accounts
12 |
13 | Checking Balance
14 |
15 |
16 |
17 | Savings Balance
18 |
19 |
20 |
21 | Account list
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/examples/banking/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Banking Example with Classes and Interfaces",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/banking/scripts/account.ts:
--------------------------------------------------------------------------------
1 | class Account {
2 | private _balance: number = 0;
3 | private _title: string;
4 |
5 | constructor(title: string) {
6 | this._title = title;
7 | }
8 |
9 | deposit(amount: number) {
10 | this._balance += amount;
11 | }
12 |
13 | widthdrawal(amount: number) : number {
14 | if (this._balance > amount) {
15 | this._balance -= amount;
16 | return amount;
17 | }
18 | else return 0;
19 | }
20 |
21 | get accountInfo() {
22 | return {
23 | routingNumber: Constants.ROUTING_NUMBER,
24 | bankNumber: Constants.BANK_NUMBER
25 | }
26 | }
27 |
28 | get balance() {
29 | return this._balance;
30 | }
31 |
32 | set balance(val: number) {
33 | this._balance = val;
34 | }
35 |
36 | get title() {
37 | return this._title;
38 | }
39 |
40 | set title(val: string) {
41 | this._title = val;
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/examples/banking/scripts/accountList.ts:
--------------------------------------------------------------------------------
1 |
2 | class AccountList {
3 | _accountList: IAccount[] = [];
4 |
5 | add(account: IAccount) {
6 | this._accountList.push(account);
7 | }
8 |
9 | getAccounts(): IAccount[] {
10 | return this._accountList;
11 | }
12 | }
13 |
14 | var acctsHtml: string = '';
15 | var accountsDiv = $('#accounts');
16 | var checkingAcct = new CheckingAccount('Jane Doe Checking');
17 | var savingsAcct = new SavingsAccount('Jane Doe Savings', 2);
18 |
19 | var accList = new AccountList();
20 | accList.add(checkingAcct);
21 | accList.add(savingsAcct);
22 |
23 | accList.getAccounts().forEach((acct, index) => {
24 | acctsHtml += acct.title + '
';
25 | });
26 | accountsDiv.html(acctsHtml);
27 |
28 |
--------------------------------------------------------------------------------
/examples/banking/scripts/arrayType.ts:
--------------------------------------------------------------------------------
1 | interface AccountArray {
2 | [index: number]: IAccount;
3 | length: number;
4 | }
5 |
6 | var acctArray: AccountArray;
7 | acctArray = [new CheckingAccount('Checking Account'), new SavingsAccount('Savings Account', 2)];
8 |
9 | for (var i = 0; i < acctArray.length; i++) {
10 | var title = acctArray[i].title;
11 | console.log(title);
12 | }
--------------------------------------------------------------------------------
/examples/banking/scripts/bankingAccount.ts:
--------------------------------------------------------------------------------
1 | class BankingAccount implements IAccount{
2 | private _balance: number = 0;
3 | private _title: string;
4 |
5 | constructor(title: string) {
6 | this._title = title;
7 | }
8 |
9 | deposit(amount: number) {
10 | this._balance += amount;
11 | }
12 |
13 | widthdrawal(amount: number) : number {
14 | if (this._balance > amount) {
15 | this._balance -= amount;
16 | return amount;
17 | }
18 | else return 0;
19 | }
20 |
21 | get accountInfo() : IAccountInfo {
22 | return {
23 | routingNumber: Constants.ROUTING_NUMBER,
24 | bankNumber: Constants.BANK_NUMBER
25 | }
26 | }
27 |
28 | get balance() {
29 | return this._balance;
30 | }
31 |
32 | set balance(val: number) {
33 | this._balance = val;
34 | }
35 |
36 | get title() {
37 | return this._title;
38 | }
39 |
40 | set title(val: string) {
41 | this._title = val;
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/examples/banking/scripts/checkingAccount.ts:
--------------------------------------------------------------------------------
1 |
2 | class CheckingAccount extends BankingAccount {
3 | constructor(title: string) {
4 | super(title);
5 | }
6 | }
7 |
8 | var account = new CheckingAccount('Jane Doe Checking');
9 | account.deposit(1000);
10 | account.widthdrawal(500);
11 | var div = $('#checking');
12 | div.html('$' + account.balance.toFixed(2));
--------------------------------------------------------------------------------
/examples/banking/scripts/constants.ts:
--------------------------------------------------------------------------------
1 | class Constants {
2 | static get ROUTING_NUMBER(): string { return '1231A4433Y2'; }
3 | static get BANK_NUMBER(): number { return 100008374; }
4 | }
--------------------------------------------------------------------------------
/examples/banking/scripts/iAccount.ts:
--------------------------------------------------------------------------------
1 | interface IAccountInfo {
2 | routingNumber: TRouteNumber;
3 | bankNumber: TBankNumber;
4 | }
5 |
6 | interface IDepositWithdrawal {
7 | deposit(amount: number): void;
8 | widthdrawal(amount: number): number;
9 | }
10 |
11 | interface IAccount extends IDepositWithdrawal {
12 | accountInfo: IAccountInfo;
13 | balance : number;
14 | title: string;
15 | internalId?: number;
16 | }
17 |
18 |
19 |
--------------------------------------------------------------------------------
/examples/banking/scripts/list.ts:
--------------------------------------------------------------------------------
1 |
2 | class ListOfNumbers {
3 | _items: number[] = [];
4 |
5 | add(item: number) {
6 | this._items.push(item);
7 | }
8 |
9 | getItems(): number[] {
10 | return this._items;
11 | }
12 | }
13 |
14 | class ListOfString {
15 | _items: string[] = [];
16 |
17 | add(item: string) {
18 | this._items.push(item);
19 | }
20 |
21 | getItems(): string[] {
22 | return this._items;
23 | }
24 | }
25 |
26 | //Generic list
27 | //With constraint
28 | //class List {
29 | class List {
30 | _items: T[] = [];
31 |
32 | add(item: T) {
33 | this._items.push(item);
34 | }
35 |
36 | getItems(): T[] {
37 | return this._items;
38 | }
39 | }
40 |
41 | //Constrain to a type that implements IAccount
42 | class ListWithConstraint {
43 | _items: T[] = [];
44 |
45 | add(item: T) {
46 | this._items.push(item);
47 | }
48 |
49 | getItems(): T[] {
50 | return this._items;
51 | }
52 | }
53 |
54 | var acctsHtml: string = '';
55 | var accountsDiv = $('#accounts');
56 | var checkingAcct = new CheckingAccount('Jane Doe Checking');
57 | var savingsAcct = new SavingsAccount('Jane Doe Savings', 2);
58 |
59 | var accountList = new List();
60 | accountList.add(checkingAcct);
61 | accountList.add(savingsAcct);
62 |
63 | accountList.getItems().forEach((acct, index) => {
64 | acctsHtml += acct.title + '
';
65 | });
66 | accountsDiv.html(acctsHtml);
67 |
68 |
69 |
--------------------------------------------------------------------------------
/examples/banking/scripts/savingsAccount.ts:
--------------------------------------------------------------------------------
1 | class SavingsAccount extends BankingAccount {
2 | private _interestRate: number;
3 |
4 | constructor(title: string, interestRate: number) {
5 | super(title);
6 | this._interestRate = interestRate;
7 | }
8 |
9 | addInterest() {
10 | this.balance = this.balance + (this.balance * (this._interestRate / 100));
11 | }
12 | }
13 |
14 | var savings = new SavingsAccount('Jane Doe', 2.5);
15 | savings.deposit(1000);
16 | savings.addInterest();
17 | var savingsDiv = $('#savings');
18 | savingsDiv.html('$' + savings.balance.toFixed(2) + ' (after interest added)');
--------------------------------------------------------------------------------
/examples/banking/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/basic-types/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Basic Types
7 |
8 |
9 |
10 | Basic Types in TypeScript
11 | View the developer tools console to see the output.
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/examples/basic-types/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Working with TypeScript Types",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/basic-types/scripts/basicTypes.ts:
--------------------------------------------------------------------------------
1 | var x: number = 5;
2 | var y: number = 5;
3 |
4 | var isLoaded: boolean = false;
5 |
6 | var firstName: string = 'John';
7 | var lastName: string = 'Doe';
8 |
9 | var pets: string[] = ['Fido', 'Lassie', 'Rover'];
10 |
11 | var info: any = { address: '1234 Anywhere St.', city: 'Seattle' };
12 |
13 | window.onload = function () {
14 | var z = x + y;
15 | console.log('x + y = ' + z);
16 | console.log('isLoaded = ' + isLoaded);
17 | console.log('Pets List:');
18 | for (var i: number = 0; i < pets.length; i++) {
19 | console.log(pets[i]);
20 | }
21 | console.log('Info: ' + info.address + ' ' + info.city);
22 | };
--------------------------------------------------------------------------------
/examples/basic-types/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/calculator-jquery/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Using TypeScript
5 |
6 |
7 | TypeScript Calculator
8 |
9 |
10 | X:
11 | Y:
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/examples/calculator-jquery/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "jQuery Calculator Example",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/calculator-jquery/scripts/calculatorJQuery.ts:
--------------------------------------------------------------------------------
1 | $(document).ready(function () {
2 | var calc = new CalculatorjQuery('X','Y','Output');
3 | });
4 |
5 | class CalculatorjQuery {
6 | private x : JQuery;
7 | private y : JQuery;
8 | private output : JQuery;
9 |
10 | constructor(xId: string, yId: string, outputId: string) {
11 | this.x = $('#' + xId);
12 | this.y = $('#' + yId);
13 | this.output = $('#' + outputId);
14 | this.wireEvents();
15 | }
16 |
17 | private wireEvents() {
18 | $('#Add').click(event => {
19 | this.output.html(this.add(parseInt(this.x.val().toString()), parseInt(this.y.val().toString())).toString());
20 | });
21 | $('#Subtract').click(event => {
22 | this.output.html(this.subtract(parseInt(this.x.val().toString()), parseInt(this.y.val().toString())).toString());
23 | });
24 | }
25 |
26 | add(x: number, y : number) {
27 | return x + y;
28 | }
29 |
30 | subtract(x : number, y: number) {
31 | return x - y;
32 | }
33 | }
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/examples/calculator-jquery/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/calculator/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Using TypeScript
5 |
6 |
7 | TypeScript Calculator
8 |
9 |
10 | X:
11 | Y:
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/examples/calculator/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Calculator Example",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/calculator/scripts/calculator.ts:
--------------------------------------------------------------------------------
1 | class Calculator {
2 | private x : HTMLInputElement;
3 | private y : HTMLInputElement;
4 | private output : HTMLSpanElement;
5 |
6 | constructor(xId: string, yId: string, outputId: string) {
7 | this.x = document.getElementById(xId);
8 | this.y = document.getElementById(yId);
9 | this.output = document.getElementById(outputId);
10 | this.wireEvents();
11 | }
12 |
13 | wireEvents() {
14 | document.getElementById('Add').addEventListener('click',
15 | event => {
16 | this.output.innerHTML = this.add(parseInt(this.x.value), parseInt(this.y.value)).toString()
17 | });
18 | document.getElementById('Subtract').addEventListener('click',
19 | event => {
20 | this.output.innerHTML = this.subtract(parseInt(this.x.value), parseInt(this.y.value)).toString()
21 | });
22 | }
23 |
24 | add(x: number, y : number) {
25 | return x + y;
26 | }
27 |
28 | subtract(x : number, y: number) {
29 | return x - y;
30 | }
31 | }
32 |
33 | window.onload = function () {
34 | var calc = new Calculator('X','Y','Output');
35 | };
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/examples/calculator/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/class-extension/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | TypeScript HTML App
7 |
8 |
9 | Autos (shows class extension)
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/examples/class-extension/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Extending Classes",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/class-extension/scripts/classExtension.ts:
--------------------------------------------------------------------------------
1 | class Engine {
2 | constructor(public horsePower: number, public engineType: string) { }
3 |
4 | start(callback: (startStatus: boolean, engineType: string) => void) {
5 | window.setTimeout(() => {
6 | callback(true, this.engineType);
7 | }, 1000);
8 | }
9 |
10 | stop(callback: (stopStatus: boolean, engineType: string) => void) {
11 | window.setTimeout(() => {
12 | callback(true, this.engineType);
13 | }, 1000);
14 | }
15 | }
16 |
17 | class Accessory {
18 | constructor(public accessoryNumber: number, public title: string) {}
19 | }
20 |
21 | class Auto {
22 | private _basePrice: number;
23 | private _engine: Engine;
24 | make: string;
25 | model: string;
26 | accessoryList: string;
27 |
28 | constructor(basePrice: number, engine: Engine, make: string, model: string) {
29 | this.engine = engine;
30 | this.basePrice = basePrice;
31 | this.make = make;
32 | this.model = model;
33 | }
34 |
35 | calculateTotal() : number {
36 | var taxRate = .08;
37 | return this.basePrice + (taxRate * this.basePrice);
38 | }
39 |
40 | addAccessories(...accessories: Accessory[]) {
41 | this.accessoryList = '';
42 | for (var i = 0; i < accessories.length; i++) {
43 | var ac = accessories[i];
44 | this.accessoryList += ac.accessoryNumber + ' ' + ac.title + '
';
45 | }
46 | }
47 |
48 | getAccessoryList(): string {
49 | return this.accessoryList;
50 | }
51 |
52 | get basePrice(): number {
53 | return this._basePrice;
54 | }
55 |
56 | set basePrice(value: number) {
57 | if (value <= 0) throw 'price must be >= 0';
58 | this._basePrice = value;
59 | }
60 |
61 | get engine(): Engine {
62 | return this._engine;
63 | }
64 |
65 | set engine(value: Engine) {
66 | if (value == undefined) throw 'Please supply an engine.';
67 | this._engine = value;
68 | }
69 | }
70 |
71 | class Truck extends Auto {
72 | bedLength: string;
73 | fourByFour: boolean;
74 |
75 | constructor(basePrice: number, engine: Engine, make: string, model: string,
76 | bedLength: string, fourByFour: boolean) {
77 | super(basePrice, engine, make, model);
78 | this.bedLength = bedLength;
79 | this.fourByFour = fourByFour;
80 | }
81 | }
82 |
83 |
84 | window.onload = function () {
85 | var truck = new Truck(40000, new Engine(300, 'V8'), 'Chevy', 'Silverado',
86 | 'Long Bed', true);
87 | truck.addAccessories(new Accessory(1234, 'Sunroof'), new Accessory(4321, 'Towing package'));
88 | truck.engine.start((status: boolean, engineType: string) => {
89 | document.getElementById('container').innerHTML = engineType + ' was started';
90 | });
91 | };
92 |
93 |
94 |
--------------------------------------------------------------------------------
/examples/classes/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | TypeScript HTML App
6 |
7 |
8 |
9 | Using Classes
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/examples/classes/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Working with Classes",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/classes/scripts/definingClasses.ts:
--------------------------------------------------------------------------------
1 | namespace DefiningClasses {
2 | class Engine {
3 | constructor(public horsePower: number, public engineType: string) { }
4 | }
5 |
6 | class Car {
7 | private _engine: Engine;
8 |
9 | constructor(engine: Engine) {
10 | this.engine = engine;
11 | }
12 |
13 | get engine(): Engine {
14 | return this._engine;
15 | }
16 |
17 | set engine(value: Engine) {
18 | if (value == undefined) throw 'Please supply an engine';
19 | this._engine = value;
20 | }
21 |
22 | start(): void {
23 | render('Car engine started ' + this._engine.engineType);
24 | }
25 | }
26 |
27 | function render(text: string) {
28 | document.getElementById('container').innerHTML += text + '
';
29 | }
30 |
31 | window.onload = function () {
32 | var engine = new Engine(300, 'V8');
33 | var car = new Car(engine);
34 | render(car.engine.engineType);
35 | car.start();
36 | };
37 | }
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/examples/compounder/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Using TypeScript Functions
7 |
8 |
9 |
10 |
11 |
12 |
Using TypeScript Functions
13 |
Compound Interest Calculator
14 |
15 |
16 |
20 |
21 |
Interest Rate:
22 |
23 |
24 |
28 |
31 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/examples/compounder/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Banking Example with Classes and Interfaces",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/compounder/scripts/compounder.ts:
--------------------------------------------------------------------------------
1 | (function () {
2 |
3 | //Stand-alone function
4 | function displayResult(msg: string) {
5 | result.innerHTML = msg;
6 | }
7 |
8 | //Anonymous function/method
9 | var compound = function (amt: number, rate: number, years: number): number {
10 | var months = years * 12;
11 | var yrRate: number = (rate / 12) / 100;
12 | return amt * Math.pow(1 + yrRate, months);
13 | };
14 |
15 | //Lambda function
16 | var $ = (id: any) => document.getElementById(id);
17 |
18 | var totalButton: HTMLButtonElement = $('totalButton'),
19 | amount: HTMLInputElement = $('amount'),
20 | rate: HTMLInputElement = $('rate'),
21 | years: HTMLInputElement = $('years'),
22 | result = $('result');
23 |
24 | //Lambda function
25 | totalButton.addEventListener('click',(e) => {
26 | var amountValue = parseFloat(amount.value),
27 | rateValue = parseFloat(rate.value),
28 | yearsValue = parseFloat(years.value);
29 |
30 | displayResult('$' + compound(amountValue, rateValue, yearsValue).toFixed(2));
31 | });
32 |
33 | } ());
--------------------------------------------------------------------------------
/examples/compounder/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/cookbook/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "files.exclude": {
3 | "**/scripts/*.js.map": true,
4 | "**/scripts/*.js": true
5 | }
6 | }
--------------------------------------------------------------------------------
/examples/cookbook/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "intro-to-typescript",
3 | "version": "1.0.0",
4 | "description": "Introduction to TypeScript",
5 | "scripts": {
6 | "postinstall": "",
7 | "tsc": "tsc",
8 | "tsc:w": "tsc --watch",
9 | "start": "concurrently \"npm run tsc:w\" \"superstatic\" "
10 | },
11 | "dependencies": {
12 | "superstatic": "^6.0.4"
13 | },
14 | "devDependencies": {
15 | "tslint": "^5.20.1",
16 | "typescript": "^3.7.2",
17 | "@types/jquery": "3.3.31",
18 | "concurrently": "^5.0.0"
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/examples/cookbook/readme.md:
--------------------------------------------------------------------------------
1 | ##Steps to run the application:
2 |
3 | ####Compiling TypeScript with npm:
4 |
5 | 1. Run "npm install" at the command-line from the root of the project (where the package.json file lives).
6 | 2. Run "npm start" at the command-line. This will compile all of the TypeScript files and generate .js and .map (for debugging) files.
7 | A watcher will also be created to monitor any changes in the .ts files. Leave the command-window open while doing development work.
8 | 3. Visit http://localhost:3474
--------------------------------------------------------------------------------
/examples/cookbook/src/images/cutlery.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DanWahlin/TypeScriptDemos/1786569708632176d5a33faaa40f0dac570b690f/examples/cookbook/src/images/cutlery.png
--------------------------------------------------------------------------------
/examples/cookbook/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Cook's Collections
6 |
7 |
8 |
9 |
10 |
11 |
12 |

13 |
14 |
15 |
Cook's Collections: A Cookbook App
16 |
17 |
18 | Recipe Type
19 |
20 |
23 |
24 |
25 | Description
26 |
27 |
28 | Primary Ingredient(s)
29 |
30 |
31 | Examples
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/examples/cookbook/src/json/recipeTypes.json:
--------------------------------------------------------------------------------
1 | {
2 | "recipeCategories": [
3 | {
4 | "title": "Appetizers",
5 | "foodGroups": [ { "title": "vegetable" }, { "title": "grain" }, { "title": "meat" } ],
6 | "details": "These foods are designed to awaken the palate prior to the meal. They should be savory, light, and easy to eat.",
7 | "examples": [
8 |
9 | {
10 | "name": "Potato Skins",
11 | "ingredients": [ "Potatoes", "Cheese", "Bacon", "Sour Cream" ],
12 | "prepTime": "20 minutes"
13 | },
14 |
15 | {
16 | "name": "Salsa",
17 | "ingredients": [ "Tomatoes", "Chili Peppers", "Garlic", "Cilantro" ],
18 | "prepTime": "15 minutes"
19 | },
20 |
21 | {
22 | "name": "Cheese Ball",
23 | "ingredients": [ "Cheddar Cheese", "Milk", "Butter", "Cream Cream" ],
24 | "prepTime": "20 minutes"
25 | }
26 |
27 |
28 | ]
29 | },
30 | {
31 | "title": "Pasta dishes",
32 | "foodGroups": [ { "title": "grain" } ],
33 | "details": "Pasta dishes are served as a first course in many parts of the world. They are among the most versatile of dishes and cook's can get very creative with them.",
34 | "examples": [
35 | { "name": "Pasta Bolognese", "ingredients": [ "Spaghetti", "Garlic", "Sausage", "Basil" ], "prepTime": "45 Minutes" },
36 | { "name": "Spaghetti Carbonara", "ingredients": [ "Spaghetti", "Bacon", "Parmasean Cheese", "Butter" ], "prepTime": "25 Minutes" },
37 | {
38 | "name": "Pesto",
39 | "ingredients": [ "Fetuccini", "Basil", "Parsley" ],
40 | "prepTime": "30 Minutes"
41 | }
42 | ]
43 | },
44 | {
45 | "title": "Vegetarian dishes",
46 | "foodGroups": [ { "title": "vegetable" }, { "title": "grain" } ],
47 | "details": "These dishes are not just for vegetarians. Including dishes based around vegetables, grains, or legumes help round out your meal and offer variety for those who choose not to eat meat.",
48 | "examples": [
49 | { "name": "Spanish Rice", "ingredients": [ "Rice", "Garlic", "Sweet Peppers", "Chili Powder" ], "prepTime": "25 Minutes" },
50 | { "name": "Baked Beans", "ingredients": [ "Navy Beans", "Onion", "Brown Sugar", "Mustard" ], "prepTime": "60 Minutes" },
51 | { "name": "Polenta", "ingredients": [ "Cornmeal", "Water" ], "prepTime": "30 Minutes" }
52 | ]
53 | },
54 | {
55 | "title": "Salads",
56 | "foodGroups": [ { "title": "vegetable" } ],
57 | "details": "Some cooks serve a salad course at the end of the meal. These dishes can include just about anything including a variety of cured meats and even grains.",
58 | "examples": [
59 | { "name": "Chicken Salad", "ingredients": [ "Cooked Chicken", "Onions", "Mayonnaise", "Celery" ], "prepTime": "20 Minutes" },
60 | { "name": "Taco Salad", "ingredients": [ "Tortilla Chips", "Garlic", "Ground Beef", "Chili Powder" ], "prepTime": "15 Minutes" }
61 | ]
62 | },
63 | {
64 | "title": "Meat dishes",
65 | "foodGroups": [
66 | { "title": "meat" }
67 | ],
68 | "details": "A great source of protein, well-prepared meat dishes can serve as the main course or a fancy side dish for any meal.",
69 | "examples": [
70 | { "name": "Pot Roast", "ingredients": [ "Beef Chuck", "Carrots", "Potatoes", "Tomato Juice" ], "prepTime": "15 Minutes" },
71 | { "name": "London Broil", "ingredients": [ "Flank Steak", "Vinegar", "Salt", "Garlic" ], "prepTime": "20 Minutes" },
72 | { "name": "Pork Chops", "ingredients": [ "Pork Loin", "Butter", "Milk", "Bread" ], "prepTime": "10 Minutes" }
73 |
74 | ]
75 | },
76 | {
77 | "title": "Breads",
78 | "foodGroups": [ { "title": "grain" } ],
79 | "details": "Breads provide a great source of grain and can be used to complement any meal. Many cooks prepare bread as an appetizer.",
80 | "examples": [
81 | { "name": "Sourdough Bread", "ingredients": [ "Starter", "Yeast", "Sugar", "Baking Soda" ], "prepTime": "60 Minutes" },
82 | { "name": "Banana Bread", "ingredients": [ "Flour", "Bananas", "Walnuts", "Sugar" ], "prepTime": "15 Minutes" }
83 | ]
84 |
85 | },
86 | {
87 | "title": "Sauces",
88 | "foodGroups": [ { "title": "vegetable" }, { "title": "grain" } ],
89 | "details": "While not a 'dish' in the strict sense, sauces are an integral part of a well-balanced flavor profile for most dishes. Use them with meats, vegetables, or even a dip for breads.",
90 | "examples": [
91 | { "name": "Cheese Sauce", "ingredients": [ "Cheddar Cheese", "Flour", "Water", "Milk" ], "prepTime": "20 Minutes" },
92 | { "name": "Hollandaise Sauce", "ingredients": [ "Butter", "Eggs", "Lemon Juice", "Pepper" ], "prepTime": "15 Minutes" }
93 | ]
94 | },
95 | {
96 | "title": "Desserts",
97 | "foodGroups": [ { "title": "sugar" }, { "title": "grain" } ],
98 | "details": "No meal is complete without something sweet to end the dining experience. Cooks have gotten very creative with desserts turning them into artwork that makes a meal memorable.",
99 | "examples": [
100 | { "name": "Chocolate Chip Cookies", "ingredients": [ "Flour", "Butter", "Chocolate Chips", "Sugar" ], "prepTime": "25 Minutes" },
101 | { "name": "Applesauce", "ingredients": [ "Cooking Apples", "Sugar", "Water", "Cinnamon" ], "prepTime": "25 Minutes" },
102 | { "name": "Gingerbread", "ingredients": [ "Flour", "Sugar", "Cinnamon", "Molasses" ], "prepTime": "20 Minutes" }
103 | ]
104 |
105 | }
106 |
107 | ]
108 | }
109 |
--------------------------------------------------------------------------------
/examples/cookbook/src/scripts/baseRecipeCategory.ts:
--------------------------------------------------------------------------------
1 | //TODO (INTERFACES EXERCISE)
2 | //1. Implement the IBaseRecipeCategory interface
3 | class BaseRecipeCategory implements IBaseRecipeCategory {
4 |
5 | //TODO (Properties exercise): Create "_name" (string type) and "_foodGroups" (FoodGroup[] type) member variables/fields.
6 | //Assign the "_foodGroups" field a value of [];
7 | // _name: string;
8 | // _foodGroups: FoodGroup[] = [];
9 |
10 |
11 | //TODO (Properties exercise): Create get and set blocks for "name" (string type) and "foodGroups" (FoodGroup[] type) properties.
12 | //The get block should return _name while the set block should assign the value to _name.
13 |
14 | // get name() {
15 | // return this._name;
16 | // }
17 |
18 | // set name(value: string) {
19 | // this._name = value;
20 | // }
21 |
22 | // get foodGroups() {
23 | // return this._foodGroups;
24 | // }
25 |
26 | // set foodGroups(value: FoodGroup[]) {
27 | // this._foodGroups = value;
28 | // }
29 |
30 |
31 | /*
32 | TODO (Constructors Exercise) Perform the following steps:
33 | 1. Delete the existing variables/fields and property get/set blocks currently in the class.
34 | You'll be replacing these properties with a simpler syntax and using a constructor to assign values to them.
35 | Note that you can remove the TODO (Properties Exercise) comments associated with the code if you'd like.
36 | 2. Add the following properties following the "propertyName: type;" coding style.
37 | You DO NOT need to use get/set blocks for these properties:
38 | a. Add a "name" property that is a string type
39 | b. Add a "foodGroups" property that is of type FoodGroup[] and assign it a value of [].
40 | 3. Create a new constructor that accepts "name" and "foodGroups" as parameters.
41 | 4. Within the constructor, assign the parameter values to the "name" and "foodGroups" properties respectively.
42 | */
43 |
44 | name: string;
45 | foodGroups: FoodGroup[];
46 |
47 | constructor(name: string, foodGroups: FoodGroup[]) {
48 | this.name = name;
49 | this.foodGroups = foodGroups;
50 | }
51 |
52 |
53 | }
--------------------------------------------------------------------------------
/examples/cookbook/src/scripts/bootstrapper.ts:
--------------------------------------------------------------------------------
1 | class Bootstrapper {
2 |
3 | renderer: Renderer;
4 |
5 | //1. Change the type to use IRecipeCategory instead of RecipeCategory.
6 | recipeCategories: RecipeCategories;
7 |
8 | loadRecipes() {
9 | var el = ( document.getElementById('RecipeCategory'));
10 | try {
11 | let category = this.recipeCategories.items
12 | //Find selected item by name
13 | .filter(item => item.name === el.value)
14 | //return the item
15 | .reduce(item => {
16 | //TODO (CONSTRUCTORS EXERCISE)
17 | //Change the RecipeCategory code below so that the property values are
18 | //passed into the constructor rather than set individually.
19 | var rc = new RecipeCategory({
20 | name: el.value,
21 | foodGroups: item.foodGroups,
22 | description: item.description,
23 | examples: item.examples
24 | });
25 | return rc;
26 | });
27 | this.renderer.renderCategory(category);
28 | }
29 | catch (ex) { alert(ex.message) }
30 | }
31 |
32 | init() {
33 | let categoriesSelect = ( document.getElementById('RecipeCategory'));
34 | categoriesSelect.onchange = () => this.loadRecipes();
35 |
36 | let recipeLoader = new RecipeLoader("/json/recipeTypes.json");
37 |
38 | recipeLoader.load().then((recipeData: IRecipeData) => {
39 | this.recipeCategories = recipeData.recipeCategories;
40 | this.renderer = new Renderer(recipeData.recipeCategoriesSummary);
41 | });
42 | }
43 |
44 | }
45 |
46 |
47 | window.onload = () => {
48 | var bootstrapper = new Bootstrapper();
49 | bootstrapper.init();
50 | };
51 |
52 |
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/examples/cookbook/src/scripts/foodGroup.ts:
--------------------------------------------------------------------------------
1 | class FoodGroup implements IFoodGroup {
2 |
3 | //TODO (Properties Exercise): Create a private "_name" member variable/field that is a string type
4 | //Example: private _myVariable: string;
5 | //_name: string;
6 |
7 | //TODO (Properties Exercise): Create a get and set block for a "name" property that is a string type.
8 | //The get block should return _name while the set block should assign the value to _name.
9 | // get name() {
10 | // return this._name;
11 | // }
12 |
13 | // set name(value: string) {
14 | // this._name = value;
15 | // }
16 |
17 |
18 | /*
19 | TODO (Constructors Exercise) Perform the following steps:
20 | 1. Delete the existing field and property get/set blocks currently in the class.
21 | You'll be replacing this property with a simpler syntax and using a constructor to assign a value to it.
22 | Note that you can remove the TODO (Properties Exercise) comments in the code if you'd like.
23 | 2. Add a "name" property that is a string type following the "propertyName: type;" coding style.
24 | 3. Create a new constructor that accepts "name" as a parameter (string type).
25 | 4. Within the constructor, assign the parameter value to the "name" property.
26 | */
27 |
28 | name: string;
29 |
30 | constructor(name: string) {
31 | this.name = name;
32 | }
33 |
34 | }
--------------------------------------------------------------------------------
/examples/cookbook/src/scripts/ingredient.ts:
--------------------------------------------------------------------------------
1 | class Ingredient {
2 | name: string;
3 |
4 | constructor(name: string) {
5 | this.name = name;
6 | }
7 | }
--------------------------------------------------------------------------------
/examples/cookbook/src/scripts/interfaces.ts:
--------------------------------------------------------------------------------
1 | //TODO (INTERFACES EXERCISE)
2 | //1. Create a new interface named IBaseRecipeCategory.
3 | //2. Add a name property (type string) into the interface.
4 | //3. Add a foodGroups property (type FoodGroup[]) into the interface.
5 | interface IBaseRecipeCategory {
6 | name: string;
7 | foodGroups: FoodGroup[];
8 | }
9 |
10 |
11 | //TODO (INTERFACES EXERCISE)
12 | //1. Create a new interface named IRecipeCategory that extends IBaseRecipeCategory
13 | //2. Add a description property (type string) into the interface.
14 | //3. Add a examples property (type IExample[]) into the interface.
15 | interface IRecipeCategory extends IBaseRecipeCategory {
16 | description: string;
17 | examples: IExample[];
18 | }
19 |
20 |
21 | interface IFoodGroup {
22 | name: string;
23 | }
24 |
25 | interface IExample {
26 | name: string;
27 | ingredients: Ingredient[];
28 | prepTime: string;
29 | }
30 |
31 | interface IIngredient {
32 | name: string;
33 | }
34 |
35 | interface IRecipeData {
36 | recipeCategories?: RecipeCategories;
37 | recipeCategoriesSummary?: RecipeCategories;
38 | }
39 |
40 | //TODO
41 | //Create an interface named IRecipeCategorySummary
42 | //that has the following members
43 | //text - string
44 | //title - string
45 |
46 | interface IRecipeCategorySummary {
47 | text: string;
48 | title: string;
49 | }
--------------------------------------------------------------------------------
/examples/cookbook/src/scripts/recipeCategories.ts:
--------------------------------------------------------------------------------
1 | //TODO (GENERICS EXERCISE)
2 | //1. Study how generics are used in this class.
3 | //2. If you're in VS Code, right-click on the RecipeCategories class and select "Find all References".
4 | //3. Take a moment to examine how the RecipeCategories generic class is used.
5 | class RecipeCategories {
6 | items: T[] = [];
7 | }
--------------------------------------------------------------------------------
/examples/cookbook/src/scripts/recipeCategory.ts:
--------------------------------------------------------------------------------
1 | //TODO (CONSTRUCTORS EXERCISE)
2 | //2. Delete the name and foodGroups properties from the RecipeCategory class.
3 | //1. Add code so make RecipeCategory inherit from BaseRecipeCategory
4 |
5 | //TODO (INTERFACES EXERCISE)
6 | //1. Implement the IRecipeCategory interface
7 | class RecipeCategory extends BaseRecipeCategory implements IRecipeCategory {
8 | description: string;
9 | examples: IExample[];
10 | //name: string;
11 | //foodGroups: FoodGroup[];
12 |
13 | /*
14 | TODO (Constructors exercise)
15 | 2. Create a constructor that accepts a recipeCategory parameter of type IRecipeCategory
16 | 3. Perform the following tasks inside of the constructor:
17 | a. Pass the "name" and "foodGroups"" values from the recipeCategory constructor
18 | parameter to the BaseRecipeCategory class (the base class or "super") by calling super().
19 | b. Assign the recipeCategory parameter's description property to the description property in this class.
20 | c. Assign the recipeCategory parameter's examples property to the examples property in this class.
21 |
22 | */
23 |
24 | //TODO (INTERFACES EXERCISE)
25 | //1. Change the parameter type to IRecipeCategory
26 | constructor(recipeCategory: RecipeCategory) {
27 | super(recipeCategory.name, recipeCategory.foodGroups);
28 | this.description = recipeCategory.description;
29 | this.examples = recipeCategory.examples;
30 | }
31 |
32 |
33 | }
--------------------------------------------------------------------------------
/examples/cookbook/src/scripts/recipeCategorySummary.ts:
--------------------------------------------------------------------------------
1 | class RecipeCategorySummary implements IRecipeCategorySummary {
2 | text: string;
3 | title: string;
4 |
5 | constructor(summary: IRecipeCategorySummary) {
6 | this.text = summary.text;
7 | this.title = summary.title;
8 | }
9 | }
--------------------------------------------------------------------------------
/examples/cookbook/src/scripts/recipeExample.ts:
--------------------------------------------------------------------------------
1 | //TODO (INTERFACES EXERCISE)
2 | //1. Add code to make the Example class implement IExample
3 | class Example implements IExample {
4 | name: string;
5 | ingredients: Ingredient[] = [];
6 | prepTime: string;
7 |
8 | constructor(example: IExample) {
9 | this.name = example.name;
10 | this.ingredients = example.ingredients;
11 | this.prepTime = example.prepTime;
12 | }
13 | }
14 |
15 |
16 |
--------------------------------------------------------------------------------
/examples/cookbook/src/scripts/recipeLoader.ts:
--------------------------------------------------------------------------------
1 | class RecipeLoader {
2 |
3 | constructor(public url: string) {}
4 |
5 | //TODO (GENERICS EXERCISE)
6 | //1. Change the load() function's return type to use the JQueryPromise generic
7 | // This will provide the caller with much better code help as they work with the return value.
8 | //2. If you're in VS Code, right-click on JQueryPromise and select "Peek Definition" from the menu
9 | //3. Take a moment to explore how the JQueryPromise interface uses generics
10 | load() : JQueryPromise {
11 | return $.getJSON(this.url).then((data: any) => {
12 | var recipeData = this.mapData(data);
13 | return recipeData;
14 | });
15 | }
16 |
17 | mapData(data: any) : IRecipeData {
18 | if (data) {
19 | let categories: any[] = data.recipeCategories;
20 |
21 | //TODO (INTERFACES EXERCISE)
22 | //Pass IRecipeCategory as the type to the generic below
23 | var recipeCategories = new RecipeCategories();
24 |
25 | //TODO (INTERFACES EXERCISE)
26 | //Pass IRecipeCategorySummary as the type to the generic below
27 | var recipeCategoriesSummary = new RecipeCategories();
28 |
29 | categories.forEach((category: any) => {
30 | //TODO (CONSTRUCTORS EXERCISE)
31 | //Change the RecipeCategory code below so that the property values are
32 | //passed into the constructor rather than set individually.
33 | let recipeCategory = new RecipeCategory({
34 | name: category.title,
35 | foodGroups: this.getFoodGroups(category),
36 | description: category.details,
37 | examples: this.getExamples(category)
38 | });
39 |
40 |
41 | recipeCategories.items.push(recipeCategory);
42 |
43 | let recipeCategorySummary = new RecipeCategorySummary({
44 | text: category.title,
45 | title: category.details
46 | });
47 | recipeCategoriesSummary.items.push(recipeCategorySummary);
48 | });
49 |
50 | return {
51 | recipeCategories: recipeCategories,
52 | recipeCategoriesSummary: recipeCategoriesSummary
53 | };
54 | }
55 | else {
56 | return null;
57 | }
58 | }
59 |
60 | getFoodGroups(category: any) : FoodGroup[] {
61 | //Map foodgroups data to TS object
62 | return category.foodGroups.map((foodGroup: any) => {
63 | //TODO (Constructors exercise)
64 | //Change the FoodGroup code below so that the property value is
65 | //passed into the constructor rather than set individually.
66 | var group = new FoodGroup(foodGroup.title);
67 | return group;
68 | });
69 | }
70 |
71 | getExamples(category: any) : IExample[] {
72 | return category.examples.map((example: any) => {
73 | return new Example({
74 | name: example.name,
75 | ingredients: this.getIngredients(example),
76 | prepTime: example.prepTime
77 | });
78 | });
79 | }
80 |
81 | getIngredients(example: any): Ingredient[] {
82 | return example.ingredients.map((value: any) => {
83 | return new Ingredient(value);
84 | });
85 | }
86 | }
--------------------------------------------------------------------------------
/examples/cookbook/src/scripts/renderer.ts:
--------------------------------------------------------------------------------
1 | class Renderer {
2 |
3 | constructor(public recipeCategoriesSummary: RecipeCategories) {
4 | if (recipeCategoriesSummary) {
5 | this.renderCategories(recipeCategoriesSummary);
6 | }
7 | else {
8 | this.renderError();
9 | }
10 | }
11 |
12 | //TODO
13 | //Example how the RecipeCategories generic is used.
14 | renderCategories(recipeCategoriesSummary: RecipeCategories) {
15 | var recipeSelect = document.getElementById('RecipeCategory');
16 | recipeCategoriesSummary.items.forEach((category) => {
17 | var opt = document.createElement('option');
18 | opt.setAttribute('title', category.title);
19 | opt.innerHTML = category.text;
20 | recipeSelect.appendChild(opt);
21 | });
22 | }
23 |
24 | //TODO (INTERFACES EXERCISE)
25 | //1. Change the category parameter type to IRecipeCategory
26 | renderCategory(category: IRecipeCategory) {
27 | //Update foodgroups bullet points
28 | var foodGroups = ( document.getElementById('FoodGroups'));
29 | foodGroups.value = '';
30 | var html = '';
31 | for (var i = 0, len = category.foodGroups.length; i < len; i++) {
32 | html += '- ' + category.foodGroups[i].name + '
';
33 | }
34 | foodGroups.innerHTML = html + '
';
35 |
36 | //Update description
37 | var el = ( document.getElementById('recipeDesc'));
38 | el.innerHTML = category.description;
39 |
40 | this.renderExamples(category);
41 |
42 | }
43 |
44 | //TODO (INTERFACES EXERCISE)
45 | //1. Change the category parameter type to IRecipeCategory
46 | renderExamples(category: IRecipeCategory) {
47 | //Update examples
48 | var examples = ( document.getElementById('examples'));
49 | examples.value = '';
50 |
51 | var html = '';
52 | for (var i = 0, len = category.examples.length; i < len; i++) {
53 | var example = category.examples[i];
54 | var ingredients = example.ingredients.map((ingredient) => {
55 | return ingredient.name;
56 | });
57 |
58 | html += '- ' +
59 | '
' + example.name + '
' +
60 | 'Ingredients: ' + ingredients.join(', ') +
61 | '
Preparation Time: ' + example.prepTime +
62 | ' ';
63 | }
64 |
65 | examples.innerHTML = html + '
';
66 | }
67 |
68 | renderError() {
69 | var examples = ( document.getElementById('examples'));
70 | examples.value = 'Unable to load data!';
71 | }
72 | }
--------------------------------------------------------------------------------
/examples/cookbook/src/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 40px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | textarea
11 | {
12 | width: 200px;
13 | height: 100px;
14 |
15 | margin-top: 5px;
16 | }
17 |
18 | .foodGroups
19 | {
20 | /*float:left*/
21 | }
22 |
23 | .logoImg
24 | {
25 | float:left;
26 | margin-bottom: 5px;
27 | margin-right: 5px;
28 | }
29 | .examples
30 | {
31 | float:left;
32 | }
33 |
--------------------------------------------------------------------------------
/examples/cookbook/superstatic.json:
--------------------------------------------------------------------------------
1 | {
2 | "public": "src"
3 | }
4 |
--------------------------------------------------------------------------------
/examples/cookbook/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "system",
5 | "moduleResolution": "node",
6 | "sourceMap": true,
7 | "emitDecoratorMetadata": true,
8 | "experimentalDecorators": true,
9 | "removeComments": false,
10 | "noImplicitAny": true,
11 | "suppressImplicitAnyIndexErrors": true
12 | },
13 | "exclude": [
14 | "node_modules"
15 | ]
16 | }
--------------------------------------------------------------------------------
/examples/generics/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Simple TypeScript Class
7 |
8 |
9 |
10 |
11 | Generics Demo
12 | View the developer tools console to see the output.
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/examples/generics/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Generics",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/generics/scripts/generics.ts:
--------------------------------------------------------------------------------
1 | //Normal way
2 | var numbers: number[] = [];
3 | var names: string[] = [];
4 |
5 | //Generics way
6 | var numbers = new Array();
7 | numbers.push(1);
8 | numbers.push(2);
9 |
10 | var names = new Array();
11 | names.push('Jane');
12 | names.push('John');
13 |
14 | numbers.forEach((n) => console.log(n));
15 | names.forEach((n) => console.log(n));
16 |
17 |
--------------------------------------------------------------------------------
/examples/generics/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/greeter/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Simple TypeScript Class
7 |
8 |
9 |
10 |
11 | Interface Demo (Interfaces)
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/examples/greeter/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Greeter Examples - Classes and Interfaces",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/greeter/scripts/greeter.ts:
--------------------------------------------------------------------------------
1 | interface IMessage {
2 | greeting: string;
3 | }
4 |
5 | interface IGreet {
6 | greet(msg: IMessage): void;
7 | }
8 |
9 |
10 | class Greeter implements IGreet {
11 | element: HTMLElement;
12 |
13 | constructor(element: HTMLElement) {
14 | this.element = element;
15 | }
16 |
17 | greet(msg: IMessage) {
18 | this.element.innerHTML = msg.greeting;
19 | }
20 | }
21 |
22 | window.onload = () => {
23 | var el = document.getElementById('content');
24 | var greeter = new Greeter(el);
25 | greeter.greet({ greeting: 'Hello from the Greeter Class!' });
26 | };
--------------------------------------------------------------------------------
/examples/greeter/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/interfaces/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Using Interfaces
6 |
7 |
8 |
9 | Using Interfaces
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/examples/interfaces/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Using Interfaces",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/interfaces/scripts/interfaces.ts:
--------------------------------------------------------------------------------
1 | namespace Interfaces {
2 |
3 | export interface IEngine {
4 | start(callback: (startStatus: boolean, engineType: string) => void): void;
5 | stop(callback: (stopStatus: boolean, engineType: string) => void): void;
6 | }
7 |
8 | export interface IAutoOptions {
9 | basePrice: number;
10 | engine: IEngine;
11 | state: string;
12 | make: string;
13 | model: string;
14 | year: number;
15 | }
16 |
17 | export interface ITruckOptions extends IAutoOptions {
18 | bedLength: string;
19 | fourByFour: boolean;
20 | }
21 |
22 | export class Engine implements IEngine {
23 | constructor(public horsePower: number, public engineType: string) { }
24 |
25 | start(callback: (startStatus: boolean, engineType: string) => void) {
26 | window.setTimeout(() => {
27 | callback(true, this.engineType);
28 | }, 1000);
29 | }
30 |
31 | stop(callback: (stopStatus: boolean, engineType: string) => void) {
32 | window.setTimeout(() => {
33 | callback(true, this.engineType);
34 | }, 1000);
35 | }
36 | }
37 |
38 | export class CustomEngine implements IEngine {
39 | start(callback: (startStatus: boolean, engineType: string) => void) {
40 | window.setTimeout(() => {
41 | callback(true, 'Custom Engine');
42 | }, 1000);
43 | }
44 |
45 | stop(callback: (stopStatus: boolean, engineType: string) => void) {
46 | window.setTimeout(() => {
47 | callback(true, 'Custom Engine');
48 | }, 1000);
49 | }
50 | }
51 |
52 | export class Accessory {
53 | constructor(public accessoryNumber: number, public title: string) { }
54 | }
55 |
56 | export class Auto {
57 | private _basePrice: number;
58 | private _engine: IEngine;
59 | state: string;
60 | make: string;
61 | model: string;
62 | year: number;
63 | accessoryList: string;
64 |
65 | constructor(options: IAutoOptions) {
66 | this.engine = options.engine;
67 | this.basePrice = options.basePrice;
68 | this.state = options.state;
69 | this.make = options.make;
70 | this.model = options.model;
71 | this.year = options.year;
72 | }
73 |
74 | calculateTotal(): number {
75 | var taxRate = .08;
76 | return this.basePrice + (taxRate * this.basePrice);
77 | }
78 |
79 | addAccessories(...accessories: Accessory[]) {
80 | this.accessoryList = '';
81 | for (var i = 0; i < accessories.length; i++) {
82 | var ac = accessories[i];
83 | this.accessoryList += ac.accessoryNumber + ' ' + ac.title + '
';
84 | }
85 | }
86 |
87 | getAccessoryList(): string {
88 | return this.accessoryList;
89 | }
90 |
91 | get basePrice(): number {
92 | return this._basePrice;
93 | }
94 |
95 | set basePrice(value: number) {
96 | if (value <= 0) throw 'price must be >= 0';
97 | this._basePrice = value;
98 | }
99 |
100 | get engine(): IEngine {
101 | return this._engine;
102 | }
103 |
104 | set engine(value: IEngine) {
105 | if (value == undefined) throw 'Please supply an engine.';
106 | this._engine = value;
107 | }
108 | }
109 |
110 | export class Truck extends Auto {
111 | bedLength: string;
112 | fourByFour: boolean;
113 |
114 | constructor(options: ITruckOptions) {
115 | super(options);
116 | this.bedLength = options.bedLength;
117 | this.fourByFour = options.fourByFour;
118 | }
119 | }
120 |
121 | }
122 |
123 | window.onload = function () {
124 | var truck = new Interfaces.Truck({
125 | engine: new Interfaces.Engine(250, 'V6'),
126 | basePrice: 45000,
127 | state: 'Arizona',
128 | make: 'Ford',
129 | model: 'F-150',
130 | year: 2013,
131 | bedLength: 'Short bed',
132 | fourByFour: true
133 | });
134 |
135 | alert(truck.bedLength);
136 |
137 | };
138 |
--------------------------------------------------------------------------------
/examples/modules-barrels/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Using TypeScript Classes
8 |
9 |
10 |
11 |
12 | Bank Accounts
13 |
14 | Checking Balance
15 |
16 |
17 |
18 | Savings Balance
19 |
20 |
21 |
22 | Account list
23 |
24 |
25 |
26 |
37 |
38 |
--------------------------------------------------------------------------------
/examples/modules-barrels/scripts/account/accountList.ts:
--------------------------------------------------------------------------------
1 | import { IAccount } from './iAccount';
2 |
3 | export class AccountList {
4 | _accountList: IAccount[] = [];
5 |
6 | add(account: IAccount) {
7 | this._accountList.push(account);
8 | }
9 |
10 | getAccounts(): IAccount[] {
11 | return this._accountList;
12 | }
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/examples/modules-barrels/scripts/account/bankingAccount.ts:
--------------------------------------------------------------------------------
1 | import { IAccount, IAccountInfo } from './iAccount';
2 |
3 | export class BankingAccount implements IAccount {
4 | private _balance: number = 0;
5 | private _title: string;
6 |
7 | constructor(title: string) {
8 | this._title = title;
9 | }
10 |
11 | deposit(amount: number) {
12 | this._balance += amount;
13 | }
14 |
15 | widthdrawal(amount: number) : number {
16 | if (this._balance > amount) {
17 | this._balance -= amount;
18 | return amount;
19 | }
20 | else return 0;
21 | }
22 |
23 | get accountInfo() : IAccountInfo {
24 | return {
25 | routingNumber: Constants.ROUTING_NUMBER,
26 | bankNumber: Constants.BANK_NUMBER
27 | }
28 | }
29 |
30 | get balance() {
31 | return this._balance;
32 | }
33 |
34 | set balance(val: number) {
35 | this._balance = val;
36 | }
37 |
38 | get title() {
39 | return this._title;
40 | }
41 |
42 | set title(val: string) {
43 | this._title = val;
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/examples/modules-barrels/scripts/account/checkingAccount.ts:
--------------------------------------------------------------------------------
1 | import { BankingAccount } from './bankingAccount';
2 |
3 | export class CheckingAccount extends BankingAccount {
4 | constructor(title: string) {
5 | super(title);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/examples/modules-barrels/scripts/account/iAccount.ts:
--------------------------------------------------------------------------------
1 | export interface IAccountInfo {
2 | routingNumber: TRouteNumber;
3 | bankNumber: TBankNumber;
4 | }
5 |
6 | export interface IDepositWithdrawal {
7 | deposit(amount: number): void;
8 | widthdrawal(amount: number): number;
9 | }
10 |
11 | export interface IAccount extends IDepositWithdrawal {
12 | accountInfo: IAccountInfo;
13 | balance : number;
14 | title: string;
15 | internalId?: number;
16 | }
17 |
18 |
19 |
--------------------------------------------------------------------------------
/examples/modules-barrels/scripts/account/index.ts:
--------------------------------------------------------------------------------
1 | export * from './accountList';
2 | export * from './bankingAccount';
3 | export * from './checkingAccount';
4 | export * from './savingsAccount';
5 |
--------------------------------------------------------------------------------
/examples/modules-barrels/scripts/account/savingsAccount.ts:
--------------------------------------------------------------------------------
1 | import { BankingAccount } from './bankingAccount';
2 |
3 | export class SavingsAccount extends BankingAccount {
4 | private _interestRate: number;
5 |
6 | constructor(title: string, interestRate: number) {
7 | super(title);
8 | this._interestRate = interestRate;
9 | }
10 |
11 | addInterest() {
12 | this.balance = this.balance + (this.balance * (this._interestRate / 100));
13 | }
14 | }
15 |
16 |
--------------------------------------------------------------------------------
/examples/modules-barrels/scripts/constants.ts:
--------------------------------------------------------------------------------
1 | export class Constants {
2 | static get ROUTING_NUMBER(): string { return '1231A4433Y2'; }
3 | static get BANK_NUMBER(): number { return 100008374; }
4 | }
--------------------------------------------------------------------------------
/examples/modules-barrels/scripts/main.ts:
--------------------------------------------------------------------------------
1 | import { CheckingAccount, AccountList, SavingsAccount } from './account/index';
2 |
3 | // import { CheckingAccount } from './account/checkingAccount';
4 | // import { SavingsAccount } from './account/savingsAccount';
5 | // import { AccountList } from './account/accountList';
6 |
7 | class Bootstrapper {
8 |
9 | $(selector: string) {
10 | return document.querySelector(selector);
11 | }
12 |
13 | renderAccounts() {
14 | let acctsHtml: string = '';
15 | const accountsDiv = this.$('#accounts');
16 | const checkingAcct = new CheckingAccount('Jane Doe Checking');
17 | const savingsAcct = new SavingsAccount('Jane Doe Savings', 2);
18 |
19 | const accList = new AccountList();
20 | accList.add(checkingAcct);
21 | accList.add(savingsAcct);
22 |
23 | accList.getAccounts().forEach((acct, index) => {
24 | acctsHtml += acct.title + '
';
25 | });
26 | accountsDiv.innerHTML = acctsHtml;
27 | }
28 |
29 |
30 | renderChecking() {
31 | const account = new CheckingAccount('Jane Doe Checking');
32 | account.deposit(1000);
33 | account.widthdrawal(500);
34 | const div = this.$('#checking').innerHTML = '$' + account.balance.toFixed(2);
35 | }
36 |
37 | renderSavings() {
38 | const savings = new SavingsAccount('Jane Doe', 2.5);
39 | savings.deposit(1000);
40 | savings.addInterest();
41 | const savingsDiv = this.$('#savings').innerHTML = '$' +
42 | savings.balance.toFixed(2) +
43 | ' (after interest added)';
44 | }
45 | }
46 |
47 | const bootstrapper = new Bootstrapper();
48 | bootstrapper.renderAccounts();
49 | bootstrapper.renderChecking();
50 | bootstrapper.renderSavings();
51 |
--------------------------------------------------------------------------------
/examples/modules-barrels/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/modules-simple/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Using TypeScript Classes
7 |
8 |
9 |
10 |
11 | Simple Modules Example
12 |
13 | Depositing $100...
14 |
15 | Account Balance: $
16 |
17 |
18 |
29 |
30 |
--------------------------------------------------------------------------------
/examples/modules-simple/scripts/bankingAccount.ts:
--------------------------------------------------------------------------------
1 | import { IAccount } from './iAccount';
2 |
3 | export class BankingAccount {
4 | private _balance: number = 0;
5 | private _title: string;
6 |
7 | constructor(title: string) {
8 | this._title = title;
9 | }
10 |
11 | deposit(amount: number) {
12 | this._balance += amount;
13 | }
14 |
15 | widthdrawal(amount: number) : number {
16 | if (this._balance > amount) {
17 | this._balance -= amount;
18 | return amount;
19 | }
20 | else return 0;
21 | }
22 |
23 | get accountInfo() : IAccountInfo {
24 | return {
25 | routingNumber: Constants.ROUTING_NUMBER,
26 | bankNumber: Constants.BANK_NUMBER
27 | }
28 | }
29 |
30 | get balance() {
31 | return this._balance;
32 | }
33 |
34 | set balance(val: number) {
35 | this._balance = val;
36 | }
37 |
38 | get title() {
39 | return this._title;
40 | }
41 |
42 | set title(val: string) {
43 | this._title = val;
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/examples/modules-simple/scripts/iAccount.ts:
--------------------------------------------------------------------------------
1 | export interface IAccountInfo {
2 | routingNumber: TRouteNumber;
3 | bankNumber: TBankNumber;
4 | }
5 |
6 | export interface IDepositWithdrawal {
7 | deposit(amount: number): void;
8 | widthdrawal(amount: number): number;
9 | }
10 |
11 | export interface IAccount extends IDepositWithdrawal {
12 | accountInfo: IAccountInfo;
13 | balance : number;
14 | title: string;
15 | internalId?: number;
16 | }
17 |
18 |
19 |
--------------------------------------------------------------------------------
/examples/modules-simple/scripts/main.ts:
--------------------------------------------------------------------------------
1 | import { BankingAccount } from './bankingAccount';
2 |
3 | const ba = new BankingAccount('Checking');
4 | ba.deposit(100);
5 |
6 | document.getElementById('balance').innerHTML = ba.balance.toString();
7 |
--------------------------------------------------------------------------------
/examples/modules-simple/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/modules-starter/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Using Modules - Starter
7 |
8 |
9 |
10 |
11 | Simple Modules Example (starter - no modules exist yet)
12 |
13 |
14 |
15 |
16 |
27 |
28 |
--------------------------------------------------------------------------------
/examples/modules-starter/scripts/conference.ts:
--------------------------------------------------------------------------------
1 | import { Speaker } from './speaker';
2 |
3 | export class Conference {
4 |
5 | constructor(public name: string,
6 | public speakers: Speaker[] = [],
7 | public sessions: string[] = []) {
8 |
9 | }
10 |
11 | addSpeaker(speaker: Speaker) {
12 | this.speakers.push(speaker);
13 | }
14 |
15 | addSession(sessionName: string) {
16 | this.sessions.push(sessionName);
17 | }
18 |
19 | }
--------------------------------------------------------------------------------
/examples/modules-starter/scripts/main.ts:
--------------------------------------------------------------------------------
1 | import { Conference } from './conference';
2 | import { Speaker } from './speaker';
3 |
4 | const conference = new Conference('AngleBrackets');
5 | conference.addSession('TypeScript with John');
6 |
7 | var s1 = new Speaker('Dan the man', 'Wahlin');
8 | var s2 = new Speaker('John', 'Papa');
9 |
10 | conference.addSpeaker(s1);
11 | conference.addSpeaker(s2);
12 |
13 | document.getElementById('whatever').innerHTML = s1.firstName;
14 |
15 | console.log(conference.speakers);
--------------------------------------------------------------------------------
/examples/modules-starter/scripts/speaker.ts:
--------------------------------------------------------------------------------
1 | export class Speaker {
2 | constructor(public firstName: string,
3 | public lastName: string) {}
4 |
5 | }
6 |
7 |
--------------------------------------------------------------------------------
/examples/modules-starter/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/modules/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Using TypeScript Classes
8 |
9 |
10 |
11 |
12 | Bank Accounts
13 |
14 | Checking Balance
15 |
16 |
17 |
18 | Savings Balance
19 |
20 |
21 |
22 | Account list
23 |
24 |
25 |
26 |
37 |
38 |
--------------------------------------------------------------------------------
/examples/modules/scripts/accountList.ts:
--------------------------------------------------------------------------------
1 | import { IAccount } from './iAccount';
2 |
3 | export class AccountList {
4 | _accountList: IAccount[] = [];
5 |
6 | add(account: IAccount) {
7 | this._accountList.push(account);
8 | }
9 |
10 | getAccounts(): IAccount[] {
11 | return this._accountList;
12 | }
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/examples/modules/scripts/arrayType.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"arrayType.js","sourceRoot":"","sources":["arrayType.ts"],"names":[],"mappings":";;;QAKI,SAAS,EAGJ,CAAC,EACF,KAAK;;;;YAHb,SAAS,GAAG,CAAC,IAAI,eAAe,CAAC,kBAAkB,CAAC,EAAE,IAAI,cAAc,CAAC,iBAAiB,EAAE,CAAC,CAAC,CAAC,CAAC;YAEhG,GAAG,CAAC,CAAK,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACpC,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;gBAC/B,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YACvB,CAAC"}
--------------------------------------------------------------------------------
/examples/modules/scripts/bankingAccount.ts:
--------------------------------------------------------------------------------
1 | import { IAccount, IAccountInfo } from './iAccount';
2 |
3 | export class BankingAccount implements IAccount {
4 | private _balance: number = 0;
5 | private _title: string;
6 |
7 | constructor(title: string) {
8 | this._title = title;
9 | }
10 |
11 | deposit(amount: number) {
12 | this._balance += amount;
13 | }
14 |
15 | widthdrawal(amount: number) : number {
16 | if (this._balance > amount) {
17 | this._balance -= amount;
18 | return amount;
19 | }
20 | else return 0;
21 | }
22 |
23 | get accountInfo() : IAccountInfo {
24 | return {
25 | routingNumber: Constants.ROUTING_NUMBER,
26 | bankNumber: Constants.BANK_NUMBER
27 | }
28 | }
29 |
30 | get balance() {
31 | return this._balance;
32 | }
33 |
34 | set balance(val: number) {
35 | this._balance = val;
36 | }
37 |
38 | get title() {
39 | return this._title;
40 | }
41 |
42 | set title(val: string) {
43 | this._title = val;
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/examples/modules/scripts/checkingAccount.ts:
--------------------------------------------------------------------------------
1 | import { BankingAccount } from './bankingAccount';
2 |
3 | export class CheckingAccount extends BankingAccount {
4 | constructor(title: string) {
5 | super(title);
6 | }
7 | }
--------------------------------------------------------------------------------
/examples/modules/scripts/constants.ts:
--------------------------------------------------------------------------------
1 | export class Constants {
2 | static get ROUTING_NUMBER(): string { return '1231A4433Y2'; }
3 | static get BANK_NUMBER(): number { return 100008374; }
4 | }
--------------------------------------------------------------------------------
/examples/modules/scripts/iAccount.ts:
--------------------------------------------------------------------------------
1 | export interface IAccountInfo {
2 | routingNumber: TRouteNumber;
3 | bankNumber: TBankNumber;
4 | }
5 |
6 | export interface IDepositWithdrawal {
7 | deposit(amount: number): void;
8 | widthdrawal(amount: number): number;
9 | }
10 |
11 | export interface IAccount extends IDepositWithdrawal {
12 | accountInfo: IAccountInfo;
13 | balance : number;
14 | title: string;
15 | internalId?: number;
16 | }
17 |
18 |
19 |
--------------------------------------------------------------------------------
/examples/modules/scripts/main.ts:
--------------------------------------------------------------------------------
1 | import { CheckingAccount } from './checkingAccount';
2 | import { SavingsAccount } from './savingsAccount';
3 | import { AccountList } from './accountList';
4 |
5 | class Bootstrapper {
6 |
7 | $(selector: string) {
8 | return document.querySelector(selector);
9 | }
10 |
11 | renderAccounts() {
12 | let acctsHtml: string = '';
13 | const accountsDiv = this.$('#accounts');
14 | const checkingAcct = new CheckingAccount('Jane Doe Checking');
15 | const savingsAcct = new SavingsAccount('Jane Doe Savings', 2);
16 |
17 | const accList = new AccountList();
18 | accList.add(checkingAcct);
19 | accList.add(savingsAcct);
20 |
21 | accList.getAccounts().forEach((acct, index) => {
22 | acctsHtml += acct.title + '
';
23 | });
24 | accountsDiv.innerHTML = acctsHtml;
25 | }
26 |
27 |
28 | renderChecking() {
29 | const account = new CheckingAccount('Jane Doe Checking');
30 | account.deposit(1000);
31 | account.widthdrawal(500);
32 | const div = this.$('#checking').innerHTML = '$' + account.balance.toFixed(2);
33 | }
34 |
35 | renderSavings() {
36 | const savings = new SavingsAccount('Jane Doe', 2.5);
37 | savings.deposit(1000);
38 | savings.addInterest();
39 | const savingsDiv = this.$('#savings').innerHTML = '$' +
40 | savings.balance.toFixed(2) +
41 | ' (after interest added)';
42 | }
43 | }
44 |
45 | const bootstrapper = new Bootstrapper();
46 | bootstrapper.renderAccounts();
47 | bootstrapper.renderChecking();
48 | bootstrapper.renderSavings();
--------------------------------------------------------------------------------
/examples/modules/scripts/savingsAccount.ts:
--------------------------------------------------------------------------------
1 | import { BankingAccount } from './bankingAccount';
2 |
3 | export class SavingsAccount extends BankingAccount {
4 | private _interestRate: number;
5 |
6 | constructor(title: string, interestRate: number) {
7 | super(title);
8 | this._interestRate = interestRate;
9 | }
10 |
11 | addInterest() {
12 | this.balance = this.balance + (this.balance * (this._interestRate / 100));
13 | }
14 | }
15 |
16 |
--------------------------------------------------------------------------------
/examples/modules/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/object-oriented/1 - Course Overview/readme.md:
--------------------------------------------------------------------------------
1 | ## Course Overview
2 |
3 | This is the course overview module so there's no code here. To run the code in the
4 | course modules you'll need to have the following installed though:
5 |
6 | 1. Node.js LTS (https://nodejs.org)
7 | 2. A code editor. I use VS Code (https://code.visualstudio.com) throughout the course.
8 |
--------------------------------------------------------------------------------
/examples/object-oriented/2 - Introduction to Object-Oriented Programming in TypeScript/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "type": "chrome",
6 | "request": "launch",
7 | "name": "Launch Chrome against localhost",
8 | "url": "http://localhost:3000",
9 | "sourceMaps": true,
10 | "webRoot": "${workspaceRoot}"
11 | },
12 | {
13 | "type": "chrome",
14 | "request": "attach",
15 | "name": "Attach to Chrome",
16 | "port": 9222,
17 | "webRoot": "${workspaceRoot}"
18 | }
19 | ]
20 | }
--------------------------------------------------------------------------------
/examples/object-oriented/2 - Introduction to Object-Oriented Programming in TypeScript/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | // Place your settings in this file to overwrite default and user settings.
2 | {
3 | "files.exclude": {
4 | "**/*.js": {
5 | "when": "$(basename).ts"
6 | },
7 | "**/*.js.map": {
8 | "when": "$(basename)"
9 | }
10 | // "examples/**/*.js.map": true,
11 | // "examples/**/*.js": true
12 | }
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/2 - Introduction to Object-Oriented Programming in TypeScript/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Bank Accounts
7 |
8 |
9 |
10 |
11 |
12 |
13 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/examples/object-oriented/2 - Introduction to Object-Oriented Programming in TypeScript/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "intro-to-typescript",
3 | "version": "1.0.0",
4 | "description": "Introduction to TypeScript",
5 | "scripts": {
6 | "postinstall": "",
7 | "tsc": "tsc",
8 | "tsc:w": "tsc --watch",
9 | "webpack": "npx webpack --mode development",
10 | "webpack:w": "npx webpack --mode development --watch",
11 | "start": "lite-server"
12 | },
13 | "dependencies": {
14 | "lite-server": "^2.6.1"
15 | },
16 | "devDependencies": {
17 | "ts-loader": "^6.2.1",
18 | "tslint": "^5.20.1",
19 | "typescript": "^3.7.2",
20 | "webpack": "^4.41.2",
21 | "webpack-cli": "^3.3.12"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/examples/object-oriented/2 - Introduction to Object-Oriented Programming in TypeScript/readme.md:
--------------------------------------------------------------------------------
1 | ## Introduction to Object-Oriented Programming in TypeScript
2 |
3 | ### Steps to Run the Code
4 |
5 | 1. Run `npm install` at the command-line from the root of the `solution` directory (where the package.json file lives).
6 | 2. Run `npm run webpack:w` to start the TypeScript build process in a command window. This will compile all of the TypeScript files and generate `.js` and `.map` (for debugging) files. A watcher will also be created to monitor any changes in the .ts files. Leave the command-window open while doing development work.
7 | 3. Run `npm start` in a separate command window. This will launch a local web server and browser.
8 |
9 | **Note:** When you're done running the code press `ctrl+c` in each of the command windows you opened above to stop the running processes.
--------------------------------------------------------------------------------
/examples/object-oriented/2 - Introduction to Object-Oriented Programming in TypeScript/src/main.js:
--------------------------------------------------------------------------------
1 | // #### Create object using object literal
2 | var objLiteral = {
3 | balance: 500
4 | };
5 | // #### Create object using a class
6 | var ClassObject = /** @class */ (function () {
7 | function ClassObject() {
8 | this.balance = 1000;
9 | }
10 | return ClassObject;
11 | }());
12 | var classObj = new ClassObject();
13 | // #### Create object using a function
14 | function FunctionObject() {
15 | this.balance = 9000;
16 | }
17 | var functionObj = new FunctionObject();
18 | // #### Create object using Object.create()
19 | var objCreate = Object.create(objLiteral);
20 | var render = function () {
21 | var total = objLiteral.balance + classObj.balance + functionObj.balance + objCreate.balance;
22 | document.querySelector('#viewTemplate').innerHTML = "\n Welcome to Acme Bank!
Your account balances:
\n Object Literal Object Balance: $" + objLiteral.balance + "\n
\n Class Object Balance: $" + classObj.balance + "\n
\n Function Constructor Object Balance: $" + functionObj.balance + "\n
\n Object.create() Object Balance: $" + objCreate.balance + "\n\n
\n Total: $" + total + "\n ";
23 | }();
24 | //# sourceMappingURL=main.js.map
--------------------------------------------------------------------------------
/examples/object-oriented/2 - Introduction to Object-Oriented Programming in TypeScript/src/main.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"main.js","sourceRoot":"","sources":["main.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,IAAM,UAAU,GAAG;IACf,OAAO,EAAE,GAAG;CACf,CAAC;AAEF,mCAAmC;AACnC;IAAA;QACI,YAAO,GAAG,IAAI,CAAC;IACnB,CAAC;IAAD,kBAAC;AAAD,CAAC,AAFD,IAEC;AACD,IAAM,QAAQ,GAAG,IAAI,WAAW,EAAE,CAAC;AAEnC,sCAAsC;AACtC,SAAS,cAAc;IACnB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;AACxB,CAAC;AACD,IAAM,WAAW,GAAG,IAAI,cAAc,EAAE,CAAC;AAEzC,2CAA2C;AAC3C,IAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;AAE5C,IAAM,MAAM,GAAG;IACX,IAAM,KAAK,GAAG,UAAU,CAAC,OAAO,GAAG,QAAQ,CAAC,OAAO,GAAG,WAAW,CAAC,OAAO,GAAG,SAAS,CAAC,OAAO,CAAC;IAC9F,QAAQ,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC,SAAS,GAAG,kIAEd,UAAU,CAAC,OAAO,yDAE3B,QAAQ,CAAC,OAAO,wEAED,WAAW,CAAC,OAAO,mEAExB,SAAS,CAAC,OAAO,mEAGzB,KAAK,WACnC,CAAC;AACN,CAAC,EAAE,CAAC"}
--------------------------------------------------------------------------------
/examples/object-oriented/2 - Introduction to Object-Oriented Programming in TypeScript/src/main.ts:
--------------------------------------------------------------------------------
1 | // #### Create object using object literal
2 | const objLiteral = {
3 | balance: 500
4 | };
5 |
6 | // #### Create object using a class
7 | class ClassObject {
8 | balance = 1000;
9 | }
10 | const classObj = new ClassObject();
11 |
12 | // #### Create object using a function
13 | function FunctionObject() {
14 | this.balance = 9000;
15 | }
16 | const functionObj = new FunctionObject();
17 |
18 | // #### Create object using Object.create()
19 | const objCreate = Object.create(objLiteral);
20 |
21 | const render = function() {
22 | const total = objLiteral.balance + classObj.balance + functionObj.balance + objCreate.balance;
23 | document.querySelector('#viewTemplate').innerHTML = `
24 | Welcome to Acme Bank!
Your account balances:
25 | Object Literal Object Balance: $${objLiteral.balance}
26 |
27 | Class Object Balance: $${classObj.balance}
28 |
29 | Function Constructor Object Balance: $${functionObj.balance}
30 |
31 | Object.create() Object Balance: $${objCreate.balance}
32 |
33 |
34 | Total: $${total}
35 | `;
36 | }();
37 |
38 |
--------------------------------------------------------------------------------
/examples/object-oriented/2 - Introduction to Object-Oriented Programming in TypeScript/src/styles/styles.css:
--------------------------------------------------------------------------------
1 | html {
2 | overflow-y: scroll;
3 | overflow-x: hidden;
4 | }
5 |
6 | main {
7 | position: relative;
8 | padding-top: 20px;
9 | }
10 |
11 | .label {
12 | font-weight: bold;
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/2 - Introduction to Object-Oriented Programming in TypeScript/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "es2015",
5 | "outDir": "./dist/",
6 | "sourceMap": true,
7 | "emitDecoratorMetadata": true,
8 | "experimentalDecorators": true,
9 | "removeComments": false,
10 | "noImplicitAny": false
11 | },
12 | "exclude": [
13 | "node_modules"
14 | ]
15 | }
--------------------------------------------------------------------------------
/examples/object-oriented/2 - Introduction to Object-Oriented Programming in TypeScript/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 |
3 | module.exports = {
4 | entry: './src/main.ts',
5 | devtool: 'inline-source-map',
6 | module: {
7 | rules: [
8 | {
9 | test: /\.ts?$/,
10 | use: 'ts-loader',
11 | exclude: /node_modules/,
12 | },
13 | ],
14 | },
15 | resolve: {
16 | extensions: [ '.ts' ],
17 | },
18 | output: {
19 | filename: 'bundle.js',
20 | path: path.resolve(__dirname, 'dist'),
21 | },
22 | };
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "type": "chrome",
6 | "request": "launch",
7 | "name": "Launch Chrome against localhost",
8 | "url": "http://localhost:3000",
9 | "sourceMaps": true,
10 | "webRoot": "${workspaceRoot}"
11 | },
12 | {
13 | "type": "chrome",
14 | "request": "attach",
15 | "name": "Attach to Chrome",
16 | "port": 9222,
17 | "webRoot": "${workspaceRoot}"
18 | }
19 | ]
20 | }
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | // Place your settings in this file to overwrite default and user settings.
2 | {
3 | "files.exclude": {
4 | "**/*.js": {
5 | "when": "$(basename).ts"
6 | },
7 | "**/*.js.map": {
8 | "when": "$(basename)"
9 | }
10 | // "examples/**/*.js.map": true,
11 | // "examples/**/*.js": true
12 | }
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Bank Accounts
7 |
8 |
9 |
10 |
11 |
12 |
13 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "intro-to-typescript",
3 | "version": "1.0.0",
4 | "description": "Introduction to TypeScript",
5 | "scripts": {
6 | "postinstall": "",
7 | "tsc": "tsc",
8 | "tsc:w": "tsc --watch",
9 | "webpack": "npx webpack --mode development",
10 | "webpack:w": "npx webpack --mode development --watch",
11 | "start": "lite-server"
12 | },
13 | "dependencies": {
14 | "lite-server": "^2.6.1"
15 | },
16 | "devDependencies": {
17 | "ts-loader": "^6.2.1",
18 | "tslint": "^5.20.1",
19 | "typescript": "^3.7.2",
20 | "webpack": "^4.41.2",
21 | "webpack-cli": "^3.3.12"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/readme.md:
--------------------------------------------------------------------------------
1 | ## Classes and Objects
2 |
3 | ### Steps to Run the Code
4 |
5 | 1. Run `npm install` at the command-line from the root of the `solution` directory (where the package.json file lives).
6 | 2. Run `npm run webpack:w` to start the TypeScript build process in a command window. This will compile all of the TypeScript files and generate `.js` and `.map` (for debugging) files. A watcher will also be created to monitor any changes in the .ts files. Leave the command-window open while doing development work.
7 | 3. Run `npm start` in a separate command window. This will launch a local web server and browser.
8 |
9 | **Note:** When you're done running the code press `ctrl+c` in each of the command windows you opened above to stop the running processes.
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/src/main.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 | var checking_account_1 = require("./scripts/checking-account");
4 | var renderer_1 = require("./scripts/renderer");
5 | var Main = /** @class */ (function () {
6 | function Main( /* private renderer: Renderer */) {
7 | // Create CheckingAccount instance
8 | this.checkingAccount = new checking_account_1.CheckingAccount('John Doe Checking');
9 | this.renderAccount();
10 | }
11 | Main.prototype.renderAccount = function () {
12 | var html = "\n Checking Account
\n
\n Owner: " + this.checkingAccount.title + "\n
\n Balance: $" + this.checkingAccount.balance.toFixed(2) + "\n
\n $ \n \n \n ";
13 | renderer_1.Renderer.render(html);
14 | };
15 | Main.prototype.depositWithDrawal = function (deposit) {
16 | var amountInput = document.querySelector('#depositWithdrawalAmount');
17 | var amount = +amountInput.value;
18 | if (deposit) {
19 | this.checkingAccount.deposit(amount);
20 | }
21 | else {
22 | this.checkingAccount.withdrawal(amount);
23 | }
24 | this.renderAccount();
25 | };
26 | return Main;
27 | }());
28 | // Create main object and add handlers for it
29 | // const renderer = new Renderer(document.querySelector('#viewTemplate'));
30 | renderer_1.Renderer.viewTemplate = document.querySelector('#viewTemplate');
31 | var main = new Main( /* renderer*/);
32 | // Quick and easy way to expose a global API that can hook to the Main object
33 | // so that we can get to it from click and events and others.
34 | // Yes, there are other ways but that's not the focus of this demo
35 | window.main = main;
36 | //# sourceMappingURL=main.js.map
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/src/main.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"main.js","sourceRoot":"","sources":["main.ts"],"names":[],"mappings":";;AAAA,+DAA6D;AAC7D,+CAA8C;AAE9C;IAGI,eAAY,gCAAgC;QACxC,kCAAkC;QAClC,IAAI,CAAC,eAAe,GAAG,IAAI,kCAAe,CAAC,mBAAmB,CAAC,CAAC;QAChE,IAAI,CAAC,aAAa,EAAE,CAAC;IACzB,CAAC;IAED,4BAAa,GAAb;QACI,IAAM,IAAI,GAAG,8HAG+B,IAAI,CAAC,eAAe,CAAC,KAAK,yFAEvB,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,0TAKjF,CAAC;QACN,mBAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;IAED,gCAAiB,GAAjB,UAAkB,OAAgB;QAC9B,IAAI,WAAW,GAAqB,QAAQ,CAAC,aAAa,CAAC,0BAA0B,CAAC,CAAC;QACvF,IAAI,MAAM,GAAG,CAAC,WAAW,CAAC,KAAK,CAAC;QAChC,IAAI,OAAO,EAAE;YACT,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;SACxC;aACI;YACD,IAAI,CAAC,eAAe,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;SAC3C;QACD,IAAI,CAAC,aAAa,EAAE,CAAC;IAEzB,CAAC;IACL,WAAC;AAAD,CAAC,AApCD,IAoCC;AAED,6CAA6C;AAC7C,0EAA0E;AAC1E,mBAAQ,CAAC,YAAY,GAAG,QAAQ,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC;AAChE,IAAM,IAAI,GAAG,IAAI,IAAI,EAAC,aAAa,CAAC,CAAC;AAErC,6EAA6E;AAC7E,6DAA6D;AAC7D,kEAAkE;AAC5D,MAAO,CAAC,IAAI,GAAG,IAAI,CAAC"}
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/src/main.ts:
--------------------------------------------------------------------------------
1 | import { CheckingAccount } from './scripts/checking-account';
2 | import { Renderer } from './scripts/renderer';
3 |
4 | class Main {
5 | checkingAccount: CheckingAccount;
6 |
7 | constructor(/* private renderer: Renderer */) {
8 | // Create CheckingAccount instance
9 | this.checkingAccount = new CheckingAccount('John Doe Checking');
10 | this.renderAccount();
11 | }
12 |
13 | renderAccount() {
14 | const html = `
15 | Checking Account
16 |
17 | Owner: ${this.checkingAccount.title}
18 |
19 | Balance: $${this.checkingAccount.balance.toFixed(2)}
20 |
21 | $
22 |
23 |
24 | `;
25 | Renderer.render(html);
26 | }
27 |
28 | depositWithDrawal(deposit: boolean) {
29 | let amountInput: HTMLInputElement = document.querySelector('#depositWithdrawalAmount');
30 | let amount = +amountInput.value;
31 | if (deposit) {
32 | this.checkingAccount.deposit(amount);
33 | }
34 | else {
35 | this.checkingAccount.withdrawal(amount);
36 | }
37 | this.renderAccount();
38 |
39 | }
40 | }
41 |
42 | // Create main object and add handlers for it
43 | // const renderer = new Renderer(document.querySelector('#viewTemplate'));
44 | Renderer.viewTemplate = document.querySelector('#viewTemplate');
45 | const main = new Main(/* renderer*/);
46 |
47 | // Quick and easy way to expose a global API that can hook to the Main object
48 | // so that we can get to it from click and events and others.
49 | // Yes, there are other ways but that's not the focus of this demo
50 | (window).main = main;
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/src/scripts/checking-account.ts:
--------------------------------------------------------------------------------
1 | export class CheckingAccount {
2 | private _balance = 0; // field
3 |
4 | constructor(public title: string) { }
5 |
6 | get balance() { // get block
7 | return this._balance;
8 | }
9 |
10 | set balance(val: number) { // set block
11 | this._balance = val;
12 | }
13 |
14 | deposit(amount: number) { // function
15 | this.balance += amount;
16 | }
17 |
18 | withdrawal(amount: number) { // function
19 | this.balance -= amount;
20 | }
21 | }
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/src/scripts/renderer.ts:
--------------------------------------------------------------------------------
1 | export class Renderer {
2 | // instance way
3 | // constructor(private viewTemplate: HTMLDivElement) {
4 | // this.viewTemplate.innerHTML = 'Welcome to Acme Bank!
Your Accounts:
';
5 | // }
6 |
7 | // render(html: string) {
8 | // this.viewTemplate.innerHTML = html;
9 | // }
10 |
11 | private constructor() { }
12 |
13 | // static way
14 | static viewTemplate: HTMLDivElement;
15 |
16 | static render(html: string) {
17 | Renderer.viewTemplate.innerHTML = html;
18 | }
19 | }
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/src/styles/styles.css:
--------------------------------------------------------------------------------
1 | html {
2 | overflow-y: scroll;
3 | overflow-x: hidden;
4 | }
5 |
6 | main {
7 | position: relative;
8 | padding-top: 20px;
9 | }
10 |
11 | .label {
12 | font-weight: bold;
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "es2015",
5 | "outDir": "./dist/",
6 | "sourceMap": true,
7 | "emitDecoratorMetadata": true,
8 | "experimentalDecorators": true,
9 | "removeComments": false,
10 | "noImplicitAny": true
11 | },
12 | "exclude": [
13 | "node_modules"
14 | ]
15 | }
--------------------------------------------------------------------------------
/examples/object-oriented/3 - Classes and Objects/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 |
3 | module.exports = {
4 | entry: './src/main.ts',
5 | devtool: 'inline-source-map',
6 | module: {
7 | rules: [
8 | {
9 | test: /\.ts?$/,
10 | use: 'ts-loader',
11 | exclude: /node_modules/,
12 | },
13 | ],
14 | },
15 | resolve: {
16 | extensions: [ '.ts' ],
17 | },
18 | output: {
19 | filename: 'bundle.js',
20 | path: path.resolve(__dirname, 'dist'),
21 | },
22 | };
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "type": "chrome",
6 | "request": "launch",
7 | "name": "Launch Chrome against localhost",
8 | "url": "http://localhost:3000",
9 | "sourceMaps": true,
10 | "webRoot": "${workspaceRoot}"
11 | },
12 | {
13 | "type": "chrome",
14 | "request": "attach",
15 | "name": "Attach to Chrome",
16 | "port": 9222,
17 | "webRoot": "${workspaceRoot}"
18 | }
19 | ]
20 | }
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | // Place your settings in this file to overwrite default and user settings.
2 | {
3 | "files.exclude": {
4 | "**/*.js": {
5 | "when": "$(basename).ts"
6 | },
7 | "**/*.js.map": {
8 | "when": "$(basename)"
9 | }
10 | // "examples/**/*.js.map": true,
11 | // "examples/**/*.js": true
12 | }
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Bank Accounts
7 |
8 |
9 |
10 |
11 |
12 |
13 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "intro-to-typescript",
3 | "version": "1.0.0",
4 | "description": "Introduction to TypeScript",
5 | "scripts": {
6 | "postinstall": "",
7 | "tsc": "tsc",
8 | "tsc:w": "tsc --watch",
9 | "webpack": "npx webpack --mode development",
10 | "webpack:w": "npx webpack --mode development --watch",
11 | "start": "lite-server"
12 | },
13 | "dependencies": {
14 | "lite-server": "^2.6.1"
15 | },
16 | "devDependencies": {
17 | "ts-loader": "^6.2.1",
18 | "tslint": "^5.20.1",
19 | "typescript": "^3.7.2",
20 | "webpack": "^4.41.2",
21 | "webpack-cli": "^3.3.12"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/readme.md:
--------------------------------------------------------------------------------
1 | ## Classes and Objects
2 |
3 | ### Steps to Run the Code
4 |
5 | 1. Run `npm install` at the command-line from the root of the `solution` directory (where the package.json file lives).
6 | 2. Run `npm run webpack:w` to start the TypeScript build process in a command window. This will compile all of the TypeScript files and generate `.js` and `.map` (for debugging) files. A watcher will also be created to monitor any changes in the .ts files. Leave the command-window open while doing development work.
7 | 3. Run `npm start` in a separate command window. This will launch a local web server and browser.
8 |
9 | **Note:** When you're done running the code press `ctrl+c` in each of the command windows you opened above to stop the running processes.
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/src/main.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 | var checking_account_1 = require("./scripts/checking-account");
4 | var renderer_1 = require("./scripts/renderer");
5 | var savings_account_1 = require("./scripts/savings-account");
6 | var enums_1 = require("./scripts/enums");
7 | var account_list_1 = require("./scripts/account-list");
8 | var Main = /** @class */ (function () {
9 | function Main(renderer) {
10 | this.renderer = renderer;
11 | // Create CheckingAccount instance
12 | this.checkingAccount = new checking_account_1.CheckingAccount({
13 | id: 1,
14 | title: 'Jane Doe Checking',
15 | balance: 5000
16 | });
17 | this.savingsAccount = new savings_account_1.SavingsAccount({
18 | id: 100,
19 | title: 'Jane Doe Savings',
20 | balance: 10000,
21 | interestRate: 2.5
22 | });
23 | var html = this.renderAccounts();
24 | this.renderer.render('Welcome to Acme Bank!
Your Accounts:
' + html);
25 | }
26 | Main.prototype.renderAccounts = function () {
27 | var acctsHtml = '';
28 | var accList = new account_list_1.AccountList();
29 | accList.add(this.checkingAccount);
30 | accList.add(this.savingsAccount);
31 | accList.getAccounts().forEach(function (acct, index) {
32 | acctsHtml += acct.title + '
';
33 | });
34 | return acctsHtml;
35 | };
36 | Main.prototype.changeView = function (view) {
37 | switch (view) {
38 | case 'checking':
39 | this.currentAccount = this.checkingAccount;
40 | break;
41 | case 'savings':
42 | this.currentAccount = this.savingsAccount;
43 | break;
44 | }
45 | this.renderAccount(this.currentAccount);
46 | };
47 | Main.prototype.renderAccount = function (account) {
48 | var accountType = enums_1.AccountType[account.accountType];
49 | var html = "\n " + accountType + " Account
\n
\n Owner: " + account.title + "\n
\n Balance: $" + account.balance.toFixed(2) + "\n
\n $ \n \n \n ";
50 | this.renderer.render(html);
51 | };
52 | Main.prototype.depositWithDrawal = function (deposit) {
53 | var amountInput = document.querySelector('#depositWithdrawalAmount');
54 | var amount = +amountInput.value;
55 | var error;
56 | try {
57 | if (deposit) {
58 | this.currentAccount.deposit(amount);
59 | }
60 | else {
61 | this.currentAccount.withdrawal(amount);
62 | }
63 | }
64 | catch (e) {
65 | error = e;
66 | }
67 | this.renderAccount(this.currentAccount);
68 | if (error) {
69 | this.renderer.renderError(error.message);
70 | }
71 | };
72 | return Main;
73 | }());
74 | // Create main object and add handlers for it
75 | var renderer = new renderer_1.Renderer(document.querySelector('#viewTemplate'));
76 | var main = new Main(renderer);
77 | // Quick and easy way to expose a global API that can hook to the Main object
78 | // so that we can get to it from click and events and others.
79 | // Yes, there are other ways but that's not the focus of this demo
80 | window.main = main;
81 | //# sourceMappingURL=main.js.map
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/src/main.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"main.js","sourceRoot":"","sources":["main.ts"],"names":[],"mappings":";;AAAA,+DAA6D;AAC7D,+CAA8C;AAE9C,6DAA2D;AAC3D,yCAA8C;AAC9C,uDAAqD;AAErD;IAKI,cAAoB,QAAkB;QAAlB,aAAQ,GAAR,QAAQ,CAAU;QAClC,kCAAkC;QAClC,IAAI,CAAC,eAAe,GAAG,IAAI,kCAAe,CAAC;YACvC,EAAE,EAAE,CAAC;YACL,KAAK,EAAE,mBAAmB;YAC1B,OAAO,EAAE,IAAI;SAChB,CAAC,CAAC;QACH,IAAI,CAAC,cAAc,GAAG,IAAI,gCAAc,CAAC;YACrC,EAAE,EAAE,GAAG;YACP,KAAK,EAAE,kBAAkB;YACzB,OAAO,EAAE,KAAK;YACd,YAAY,EAAE,GAAG;SACpB,CAAC,CAAC;QACH,IAAI,IAAI,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;QACjC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,mEAAmE,GAAG,IAAI,CAAC,CAAC;IACrG,CAAC;IAED,6BAAc,GAAd;QACI,IAAI,SAAS,GAAW,EAAE,CAAC;QAC3B,IAAM,OAAO,GAAG,IAAI,0BAAW,EAAE,CAAC;QAClC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;QAClC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAEjC,OAAO,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,UAAC,IAAI,EAAE,KAAK;YACtC,SAAS,IAAI,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC;QACvC,CAAC,CAAC,CAAC;QACH,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,yBAAU,GAAV,UAAW,IAAa;QACpB,QAAQ,IAAI,EAAE;YACV,KAAK,UAAU;gBACX,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,eAAe,CAAC;gBAC3C,MAAM;YACV,KAAK,SAAS;gBACV,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;gBAC1C,MAAM;SACb;QACD,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IAC5C,CAAC;IAED,4BAAa,GAAb,UAAc,OAAoB;QAC9B,IAAM,WAAW,GAAG,mBAAW,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QACrD,IAAM,IAAI,GAAG,2BACC,WAAW,mGAEmB,OAAO,CAAC,KAAK,yFAEV,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,0TAKpE,CAAC;QACN,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IAED,gCAAiB,GAAjB,UAAkB,OAAgB;QAC9B,IAAI,WAAW,GAAqB,QAAQ,CAAC,aAAa,CAAC,0BAA0B,CAAC,CAAC;QACvF,IAAI,MAAM,GAAG,CAAC,WAAW,CAAC,KAAK,CAAC;QAChC,IAAI,KAAK,CAAC;QACV,IAAI;YACA,IAAI,OAAO,EAAE;gBACT,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;aACvC;iBACI;gBACD,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;aAC1C;SACJ;QACD,OAAO,CAAC,EAAE;YACN,KAAK,GAAG,CAAC,CAAC;SACb;QAED,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACxC,IAAI,KAAK,EAAE;YACP,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;SAC5C;IACL,CAAC;IACL,WAAC;AAAD,CAAC,AAnFD,IAmFC;AAED,6CAA6C;AAC7C,IAAM,QAAQ,GAAG,IAAI,mBAAQ,CAAC,QAAQ,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC,CAAC;AACvE,IAAM,IAAI,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC;AAEhC,6EAA6E;AAC7E,6DAA6D;AAC7D,kEAAkE;AAC5D,MAAO,CAAC,IAAI,GAAG,IAAI,CAAC"}
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/src/main.ts:
--------------------------------------------------------------------------------
1 | import { CheckingAccount } from './scripts/checking-account';
2 | import { Renderer } from './scripts/renderer';
3 | import { BankAccount } from './scripts/bank-account';
4 | import { SavingsAccount } from './scripts/savings-account';
5 | import { AccountType } from './scripts/enums';
6 | import { AccountList } from './scripts/account-list';
7 |
8 | class Main {
9 | checkingAccount: CheckingAccount;
10 | savingsAccount: SavingsAccount;
11 | currentAccount: BankAccount;
12 |
13 | constructor(private renderer: Renderer) {
14 | // Create CheckingAccount instance
15 | this.checkingAccount = new CheckingAccount({
16 | id: 1,
17 | title: 'Jane Doe Checking',
18 | balance: 5000
19 | });
20 | this.savingsAccount = new SavingsAccount({
21 | id: 100,
22 | title: 'Jane Doe Savings',
23 | balance: 10000,
24 | interestRate: 2.5
25 | });
26 | let html = this.renderAccounts();
27 | this.renderer.render('Welcome to Acme Bank!
Your Accounts:
' + html);
28 | }
29 |
30 | renderAccounts() {
31 | let acctsHtml: string = '';
32 | const accList = new AccountList();
33 | accList.add(this.checkingAccount);
34 | accList.add(this.savingsAccount);
35 |
36 | accList.getAccounts().forEach((acct, index) => {
37 | acctsHtml += acct.title + '
';
38 | });
39 | return acctsHtml;
40 | }
41 |
42 | changeView(view?: string) {
43 | switch (view) {
44 | case 'checking':
45 | this.currentAccount = this.checkingAccount;
46 | break;
47 | case 'savings':
48 | this.currentAccount = this.savingsAccount;
49 | break;
50 | }
51 | this.renderAccount(this.currentAccount);
52 | }
53 |
54 | renderAccount(account: BankAccount) {
55 | const accountType = AccountType[account.accountType];
56 | const html = `
57 | ${accountType} Account
58 |
59 | Owner: ${account.title}
60 |
61 | Balance: $${account.balance.toFixed(2)}
62 |
63 | $
64 |
65 |
66 | `;
67 | this.renderer.render(html);
68 | }
69 |
70 | depositWithDrawal(deposit: boolean) {
71 | let amountInput: HTMLInputElement = document.querySelector('#depositWithdrawalAmount');
72 | let amount = +amountInput.value;
73 | let error;
74 | try {
75 | if (deposit) {
76 | this.currentAccount.deposit(amount);
77 | }
78 | else {
79 | this.currentAccount.withdrawal(amount);
80 | }
81 | }
82 | catch (e) {
83 | error = e;
84 | }
85 |
86 | this.renderAccount(this.currentAccount);
87 | if (error) {
88 | this.renderer.renderError(error.message);
89 | }
90 | }
91 | }
92 |
93 | // Create main object and add handlers for it
94 | const renderer = new Renderer(document.querySelector('#viewTemplate'));
95 | const main = new Main(renderer);
96 |
97 | // Quick and easy way to expose a global API that can hook to the Main object
98 | // so that we can get to it from click and events and others.
99 | // Yes, there are other ways but that's not the focus of this demo
100 | (window).main = main;
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/src/scripts/account-list.ts:
--------------------------------------------------------------------------------
1 | import { BankAccount } from './bank-account';
2 |
3 | export class AccountList {
4 | _accountList: BankAccount[] = [];
5 |
6 | add(account: BankAccount) {
7 | this._accountList.push(account);
8 | }
9 |
10 | getAccounts(): BankAccount[] {
11 | return this._accountList;
12 | }
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/src/scripts/bank-account.ts:
--------------------------------------------------------------------------------
1 | import { AccountType } from './enums';
2 |
3 | export abstract class BankAccount {
4 | private _balance = 0;
5 | id: number;
6 | title: string;
7 | abstract accountType: AccountType;
8 |
9 | constructor(accountSettings: any) {
10 | this.id = accountSettings.id;
11 | this.title = accountSettings.title;
12 | this.balance = accountSettings.balance;
13 | }
14 |
15 | deposit(amount: number) {
16 | this.balance += amount;
17 | }
18 |
19 | withdrawal(amount: number) {
20 | this.balance -= amount;
21 | }
22 |
23 | abstract getAccountInfo(): any;
24 |
25 | get balance() {
26 | return this._balance;
27 | }
28 |
29 | set balance(val: number) {
30 | if (val >= 0) {
31 | this._balance = val;
32 | }
33 | else {
34 | throw Error('Balance cannot be negative!');
35 | }
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/src/scripts/checking-account.ts:
--------------------------------------------------------------------------------
1 | import { BankAccount } from "./bank-account";
2 | import { AccountType } from "./enums";
3 |
4 | export class CheckingAccount extends BankAccount {
5 | accountType = AccountType.Checking;
6 |
7 | getAccountInfo() {
8 | return {
9 |
10 | };
11 | }
12 | }
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/src/scripts/enums.ts:
--------------------------------------------------------------------------------
1 | export enum AccountType {
2 | Checking,
3 | Savings
4 | }
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/src/scripts/renderer.ts:
--------------------------------------------------------------------------------
1 | export class Renderer {
2 | constructor(private viewTemplate: HTMLDivElement) {
3 | this.viewTemplate.innerHTML = 'Welcome to Acme Bank!
Your Accounts:
';
4 | }
5 |
6 | render(html: string) {
7 | this.viewTemplate.innerHTML = html;
8 | }
9 |
10 | renderError(message: string) {
11 | this.viewTemplate.innerHTML += `
${message}
`;
12 | }
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/src/scripts/savings-account.ts:
--------------------------------------------------------------------------------
1 | import { BankAccount } from './bank-account';
2 | import { AccountType } from './enums';
3 |
4 | export class SavingsAccount extends BankAccount {
5 | private _interestRate: number;
6 | accountType = AccountType.Savings;
7 |
8 | constructor(accountSettings: any) {
9 | super(accountSettings);
10 | this._interestRate = accountSettings.interestRate;
11 |
12 | // Simulate interest over time
13 | setInterval(() => {
14 | this.addInterest();
15 | }, 60000);
16 | }
17 |
18 | getAccountInfo() {
19 | return {
20 |
21 | };
22 | }
23 |
24 | deposit(amount: number) {
25 | let newAmount = amount + (amount * (this._interestRate / 100));
26 | this.balance += newAmount;
27 | }
28 |
29 | private addInterest() {
30 | this.balance = this.balance + (this.balance * (this._interestRate / 100));
31 | }
32 | }
33 |
34 |
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/src/styles/styles.css:
--------------------------------------------------------------------------------
1 | html {
2 | overflow-y: scroll;
3 | overflow-x: hidden;
4 | }
5 |
6 | main {
7 | position: relative;
8 | padding-top: 20px;
9 | }
10 |
11 | .label {
12 | font-weight: bold;
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "es2015",
5 | "outDir": "./dist/",
6 | "sourceMap": true,
7 | "emitDecoratorMetadata": true,
8 | "experimentalDecorators": true,
9 | "removeComments": false,
10 | "noImplicitAny": true
11 | },
12 | "exclude": [
13 | "node_modules"
14 | ]
15 | }
--------------------------------------------------------------------------------
/examples/object-oriented/4 - Inheritance and Abstraction/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 |
3 | module.exports = {
4 | entry: './src/main.ts',
5 | devtool: 'inline-source-map',
6 | module: {
7 | rules: [
8 | {
9 | test: /\.ts?$/,
10 | use: 'ts-loader',
11 | exclude: /node_modules/,
12 | },
13 | ],
14 | },
15 | resolve: {
16 | extensions: [ '.ts' ],
17 | },
18 | output: {
19 | filename: 'bundle.js',
20 | path: path.resolve(__dirname, 'dist'),
21 | },
22 | };
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "type": "chrome",
6 | "request": "launch",
7 | "name": "Launch Chrome against localhost",
8 | "url": "http://localhost:3000",
9 | "sourceMaps": true,
10 | "webRoot": "${workspaceRoot}"
11 | },
12 | {
13 | "type": "chrome",
14 | "request": "attach",
15 | "name": "Attach to Chrome",
16 | "port": 9222,
17 | "webRoot": "${workspaceRoot}"
18 | }
19 | ]
20 | }
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | // Place your settings in this file to overwrite default and user settings.
2 | {
3 | "files.exclude": {
4 | "**/*.js": {
5 | "when": "$(basename).ts"
6 | },
7 | "**/*.js.map": {
8 | "when": "$(basename)"
9 | }
10 | // "examples/**/*.js.map": true,
11 | // "examples/**/*.js": true
12 | }
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/data.json:
--------------------------------------------------------------------------------
1 | {
2 | "checkingAccount": {
3 | "id": 1,
4 | "balance": 500,
5 | "title": "Jane Doe Checking"
6 | },
7 | "savingsAccount": {
8 | "id": 2,
9 | "balance": 1500,
10 | "title": "Jane Doe Savings",
11 | "interestRate": 2.5
12 | }
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Bank Accounts
7 |
8 |
9 |
10 |
11 |
12 |
13 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "intro-to-typescript",
3 | "version": "1.0.0",
4 | "description": "Introduction to TypeScript",
5 | "scripts": {
6 | "postinstall": "",
7 | "tsc": "tsc",
8 | "tsc:w": "tsc --watch",
9 | "webpack": "npx webpack --mode development",
10 | "webpack:w": "npx webpack --mode development --watch",
11 | "start": "lite-server"
12 | },
13 | "dependencies": {
14 | "lite-server": "^2.5.4"
15 | },
16 | "devDependencies": {
17 | "ts-loader": "^6.2.1",
18 | "tslint": "^5.20.1",
19 | "typescript": "^3.7.2",
20 | "webpack": "^4.41.2",
21 | "webpack-cli": "^3.3.12"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/readme.md:
--------------------------------------------------------------------------------
1 | ## Final Code Solution
2 |
3 | This is the final code solution for the course.
4 |
5 | ### Steps to Run the Code
6 |
7 | 1. Run `npm install` at the command-line from the root of the `solution` directory (where the package.json file lives).
8 | 2. Run `npm run webpack:w` to start the TypeScript build process in a command window. This will compile all of the TypeScript files and generate `.js` and `.map` (for debugging) files. A watcher will also be created to monitor any changes in the .ts files. Leave the command-window open while doing development work.
9 | 3. Run `npm start` in a separate command window. This will launch a local web server and browser.
10 |
11 | **Note:** When you're done running the code press `ctrl+c` in each of the command windows you opened above to stop the running processes.
12 |
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/images/acmebank.afphoto:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DanWahlin/TypeScriptDemos/1786569708632176d5a33faaa40f0dac570b690f/examples/object-oriented/5 - Interfaces and Polymorphism/src/images/acmebank.afphoto
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/images/acmebank.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DanWahlin/TypeScriptDemos/1786569708632176d5a33faaa40f0dac570b690f/examples/object-oriented/5 - Interfaces and Polymorphism/src/images/acmebank.jpg
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/images/atm.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DanWahlin/TypeScriptDemos/1786569708632176d5a33faaa40f0dac570b690f/examples/object-oriented/5 - Interfaces and Polymorphism/src/images/atm.jpg
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/images/checking.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DanWahlin/TypeScriptDemos/1786569708632176d5a33faaa40f0dac570b690f/examples/object-oriented/5 - Interfaces and Polymorphism/src/images/checking.jpg
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/images/savings.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DanWahlin/TypeScriptDemos/1786569708632176d5a33faaa40f0dac570b690f/examples/object-oriented/5 - Interfaces and Polymorphism/src/images/savings.jpg
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/main.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | var __assign = (this && this.__assign) || function () {
3 | __assign = Object.assign || function(t) {
4 | for (var s, i = 1, n = arguments.length; i < n; i++) {
5 | s = arguments[i];
6 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 | t[p] = s[p];
8 | }
9 | return t;
10 | };
11 | return __assign.apply(this, arguments);
12 | };
13 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15 | return new (P || (P = Promise))(function (resolve, reject) {
16 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19 | step((generator = generator.apply(thisArg, _arguments || [])).next());
20 | });
21 | };
22 | var __generator = (this && this.__generator) || function (thisArg, body) {
23 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25 | function verb(n) { return function (v) { return step([n, v]); }; }
26 | function step(op) {
27 | if (f) throw new TypeError("Generator is already executing.");
28 | while (_) try {
29 | if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30 | if (y = 0, t) op = [op[0] & 2, t.value];
31 | switch (op[0]) {
32 | case 0: case 1: t = op; break;
33 | case 4: _.label++; return { value: op[1], done: false };
34 | case 5: _.label++; y = op[1]; op = [0]; continue;
35 | case 7: op = _.ops.pop(); _.trys.pop(); continue;
36 | default:
37 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41 | if (t[2]) _.ops.pop();
42 | _.trys.pop(); continue;
43 | }
44 | op = body.call(thisArg, _);
45 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47 | }
48 | };
49 | Object.defineProperty(exports, "__esModule", { value: true });
50 | var checking_account_1 = require("./scripts/checking-account");
51 | var savings_account_1 = require("./scripts/savings-account");
52 | var account_list_1 = require("./scripts/account-list");
53 | var renderer_1 = require("./scripts/renderer");
54 | var enums_1 = require("./scripts/enums");
55 | var atm_1 = require("./scripts/atm");
56 | var Main = /** @class */ (function () {
57 | function Main(renderer) {
58 | this.renderer = renderer;
59 | }
60 | Main.prototype.loadAccounts = function () {
61 | return __awaiter(this, void 0, void 0, function () {
62 | var response, data, html;
63 | return __generator(this, function (_a) {
64 | switch (_a.label) {
65 | case 0: return [4 /*yield*/, fetch('/data.json')];
66 | case 1:
67 | response = _a.sent();
68 | return [4 /*yield*/, response.json()];
69 | case 2:
70 | data = _a.sent();
71 | this.checkingAccount = new checking_account_1.CheckingAccount(__assign({}, data.checkingAccount));
72 | this.savingsAccount = new savings_account_1.SavingsAccount(__assign({}, data.savingsAccount));
73 | this.atm = new atm_1.ATM(this.checkingAccount);
74 | html = this.renderAccounts();
75 | this.renderer.render("\n Welcome to Acme Bank!
\n \n
\n Your Accounts:
\n " + html + "\n ");
76 | return [2 /*return*/];
77 | }
78 | });
79 | });
80 | };
81 | Main.prototype.changeView = function (view) {
82 | switch (view) {
83 | case 'checking':
84 | this.currentAccount = this.checkingAccount;
85 | break;
86 | case 'savings':
87 | this.currentAccount = this.savingsAccount;
88 | break;
89 | case 'atm':
90 | this.currentAccount = this.checkingAccount;
91 | this.renderAtm();
92 | return;
93 | }
94 | this.renderAccount(this.currentAccount);
95 | };
96 | Main.prototype.renderAtm = function () {
97 | var html = "\n ATM
\n \n
\n Current Checking Account Balance: $" + this.checkingAccount.balance + "\n
\n $ \n \n \n ";
98 | this.renderer.render(html);
99 | };
100 | Main.prototype.renderAccounts = function () {
101 | var acctsHtml = '';
102 | var accList = new account_list_1.AccountList();
103 | accList.add(this.checkingAccount);
104 | accList.add(this.savingsAccount);
105 | accList.getAccounts().forEach(function (acct, index) {
106 | acctsHtml += acct.title + '
';
107 | });
108 | return acctsHtml;
109 | };
110 | Main.prototype.renderAccount = function (account) {
111 | var accountType = enums_1.AccountType[account.accountType];
112 | var html = "\n " + accountType + " Account
\n \n
\n Owner: " + account.title + "\n
\n Balance: $" + account.balance.toFixed(2) + "\n
\n $ \n \n \n ";
113 | this.renderer.render(html);
114 | };
115 | Main.prototype.depositWithDrawal = function (deposit, atm) {
116 | var amountInput = document.querySelector('#depositWithdrawalAmount');
117 | var amount = +amountInput.value;
118 | var error;
119 | try {
120 | if (deposit) {
121 | if (atm) {
122 | this.atm.deposit(amount);
123 | }
124 | else {
125 | this.currentAccount.deposit(amount);
126 | }
127 | }
128 | else {
129 | if (atm) {
130 | this.atm.withdrawal(amount);
131 | }
132 | else {
133 | this.currentAccount.withdrawal(amount);
134 | }
135 | }
136 | }
137 | catch (e) {
138 | error = e;
139 | }
140 | (atm) ? this.renderAtm() : this.renderAccount(this.currentAccount);
141 | if (error) {
142 | this.renderer.renderError(error.message);
143 | }
144 | };
145 | return Main;
146 | }());
147 | // Create main object and add handlers for it
148 | var renderer = new renderer_1.Renderer(document.querySelector('#viewTemplate'));
149 | var main = new Main(renderer);
150 | main.loadAccounts();
151 | // Quick and easy way to expose a global API that can hook to the Main object
152 | // so that we can get to it from click and events and others.
153 | // Yes, there are other ways but this gets the job done for this demo.
154 | window.main = main;
155 | //# sourceMappingURL=main.js.map
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/main.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"main.js","sourceRoot":"","sources":["main.ts"],"names":[],"mappings":"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"}
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/main.ts:
--------------------------------------------------------------------------------
1 | import { CheckingAccount } from './scripts/checking-account';
2 | import { SavingsAccount } from './scripts/savings-account';
3 | import { AccountList } from './scripts/account-list';
4 | import { BankAccount } from './scripts/bank-account';
5 | import { Renderer } from './scripts/renderer';
6 | import { AccountType } from './scripts/enums';
7 | import { ATM } from './scripts/atm';
8 |
9 | class Main {
10 | checkingAccount: CheckingAccount;
11 | savingsAccount: SavingsAccount;
12 | currentAccount: BankAccount;
13 | atm: ATM;
14 |
15 | constructor(private renderer: Renderer) { }
16 |
17 | async loadAccounts() {
18 | const response = await fetch('/data.json');
19 | const data = await response.json();
20 | this.checkingAccount = new CheckingAccount({ ...data.checkingAccount });
21 | this.savingsAccount = new SavingsAccount({ ...data.savingsAccount });
22 | this.atm = new ATM(this.checkingAccount);
23 |
24 | let html = this.renderAccounts();
25 | this.renderer.render(`
26 | Welcome to Acme Bank!
27 |
28 |
29 | Your Accounts:
30 | ${html}
31 | `);
32 | }
33 |
34 | changeView(view?: string) {
35 | switch (view) {
36 | case 'checking':
37 | this.currentAccount = this.checkingAccount;
38 | break;
39 | case 'savings':
40 | this.currentAccount = this.savingsAccount;
41 | break;
42 | case 'atm':
43 | this.currentAccount = this.checkingAccount;
44 | this.renderAtm();
45 | return;
46 | }
47 | this.renderAccount(this.currentAccount);
48 | }
49 |
50 | renderAtm() {
51 | const html = `
52 | ATM
53 |
54 |
55 | Current Checking Account Balance: $${this.checkingAccount.balance}
56 |
57 | $
58 |
59 |
60 | `;
61 | this.renderer.render(html);
62 | }
63 |
64 | renderAccounts() {
65 | let acctsHtml: string = '';
66 | const accList = new AccountList();
67 | accList.add(this.checkingAccount);
68 | accList.add(this.savingsAccount);
69 |
70 | accList.getAccounts().forEach((acct, index) => {
71 | acctsHtml += acct.title + '
';
72 | });
73 | return acctsHtml;
74 | }
75 |
76 | renderAccount(account: BankAccount) {
77 | const accountType = AccountType[account.accountType];
78 | const html = `
79 | ${accountType} Account
80 |
81 |
82 | Owner: ${account.title}
83 |
84 | Balance: $${account.balance.toFixed(2)}
85 |
86 | $
87 |
88 |
89 | `;
90 | this.renderer.render(html);
91 | }
92 |
93 | depositWithDrawal(deposit: boolean, atm?: boolean) {
94 | let amountInput: HTMLInputElement = document.querySelector('#depositWithdrawalAmount');
95 | let amount = +amountInput.value;
96 | let error;
97 | try {
98 | if (deposit) {
99 | if (atm) {
100 | this.atm.deposit(amount);
101 | }
102 | else {
103 | this.currentAccount.deposit(amount);
104 | }
105 | }
106 | else {
107 | if (atm) {
108 | this.atm.withdrawal(amount);
109 | }
110 | else {
111 | this.currentAccount.withdrawal(amount);
112 | }
113 | }
114 | }
115 | catch (e) {
116 | error = e;
117 | }
118 |
119 | (atm) ? this.renderAtm(): this.renderAccount(this.currentAccount);
120 | if (error) {
121 | this.renderer.renderError(error.message);
122 | }
123 | }
124 | }
125 |
126 | // Create main object and add handlers for it
127 | const renderer = new Renderer(document.querySelector('#viewTemplate'));
128 | const main = new Main(renderer);
129 | main.loadAccounts();
130 |
131 | // Quick and easy way to expose a global API that can hook to the Main object
132 | // so that we can get to it from click and events and others.
133 | // Yes, there are other ways but this gets the job done for this demo.
134 | (window).main = main;
135 |
136 |
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/scripts/account-list.ts:
--------------------------------------------------------------------------------
1 | import { Account } from './interfaces';
2 |
3 | export class AccountList {
4 | _accountList: Account[] = [];
5 |
6 | add(account: Account) {
7 | this._accountList.push(account);
8 | }
9 |
10 | getAccounts(): Account[] {
11 | return this._accountList;
12 | }
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/scripts/atm.ts:
--------------------------------------------------------------------------------
1 | import { DepositWithdrawal, Account } from './interfaces';
2 |
3 | export class ATM implements DepositWithdrawal {
4 |
5 | constructor(private account: Account) { }
6 |
7 | deposit(amount: number) {
8 | this.account.deposit(amount);
9 | }
10 |
11 | withdrawal(amount: number) {
12 | this.account.withdrawal(amount);
13 | }
14 | }
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/scripts/bank-account.ts:
--------------------------------------------------------------------------------
1 | import { Account, AccountInfo, AccountSettings } from './interfaces';
2 | import { Constants } from './constants';
3 | import { AccountType } from './enums';
4 |
5 | export abstract class BankAccount implements Account {
6 | id: number;
7 | title: string;
8 | private _balance = 0;
9 | abstract accountType: AccountType;
10 |
11 | constructor(accountSettings: AccountSettings) {
12 | this.id = accountSettings.id;
13 | this.title = accountSettings.title;
14 | this.balance = accountSettings.balance;
15 | }
16 |
17 | deposit(amount: number) {
18 | this.balance += amount;
19 | }
20 |
21 | withdrawal(amount: number) {
22 | this.balance -= amount;
23 | }
24 |
25 | getAccountInfo() : AccountInfo {
26 | return {
27 | routingNumber: Constants.ROUTING_NUMBER,
28 | bankNumber: Constants.BANK_NUMBER
29 | };
30 | }
31 |
32 | get balance() {
33 | return this._balance;
34 | }
35 |
36 | set balance(val: number) {
37 | if (val >= 0) {
38 | this._balance = val;
39 | }
40 | else {
41 | throw Error('Balance cannot be negative!');
42 | }
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/scripts/checking-account.ts:
--------------------------------------------------------------------------------
1 | import { BankAccount } from './bank-account';
2 | import { AccountType } from './enums';
3 |
4 | export class CheckingAccount extends BankAccount {
5 | accountType = AccountType.Checking;
6 | }
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/scripts/constants.ts:
--------------------------------------------------------------------------------
1 | export class Constants {
2 | static get ROUTING_NUMBER(): string { return '1231A4433Y2'; }
3 | static get BANK_NUMBER(): number { return 100008374; }
4 | }
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/scripts/enums.ts:
--------------------------------------------------------------------------------
1 | export enum AccountType {
2 | Checking,
3 | Savings
4 | }
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/scripts/interfaces.ts:
--------------------------------------------------------------------------------
1 | export interface AccountInfo {
2 | routingNumber: TRouteNumber;
3 | bankNumber: TBankNumber;
4 | }
5 |
6 | export interface DepositWithdrawal {
7 | deposit(amount: number): void;
8 | withdrawal(amount: number): void;
9 | }
10 |
11 | export interface AccountSettings {
12 | id: number;
13 | title: string;
14 | balance : number;
15 | interestRate?: number;
16 | accountInfo?: AccountInfo;
17 | }
18 |
19 | export interface Account extends AccountSettings, DepositWithdrawal { }
20 |
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/scripts/renderer.ts:
--------------------------------------------------------------------------------
1 | export class Renderer {
2 | constructor(private viewTemplate: HTMLDivElement) {
3 | this.viewTemplate.innerHTML = `
4 | Welcome to Acme Bank!
5 |
6 |
7 | Your Accounts:
`;
8 | }
9 |
10 | render(html: string) {
11 | this.viewTemplate.innerHTML = html;
12 | }
13 |
14 | renderError(message: string) {
15 | this.viewTemplate.innerHTML += `
${message}
`;
16 | }
17 | }
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/scripts/savings-account.ts:
--------------------------------------------------------------------------------
1 | import { BankAccount } from './bank-account';
2 | import { AccountType } from './enums';
3 | import { AccountSettings } from './interfaces';
4 |
5 |
6 | export class SavingsAccount extends BankAccount {
7 | private _interestRate: number;
8 | accountType = AccountType.Savings;
9 |
10 | constructor(accountSettings: AccountSettings) {
11 | super(accountSettings);
12 | this._interestRate = accountSettings.interestRate;
13 |
14 | // Simulate interest over time
15 | setInterval(() => {
16 | this.addInterest();
17 | }, 60000);
18 | }
19 |
20 | deposit(amount: number) {
21 | let newAmount = amount + (amount * (this._interestRate / 100));
22 | this.balance += newAmount;
23 | }
24 |
25 | private addInterest() {
26 | this.balance = this.balance + (this.balance * (this._interestRate / 100));
27 | }
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/src/styles/styles.css:
--------------------------------------------------------------------------------
1 | html {
2 | overflow-y: scroll;
3 | overflow-x: hidden;
4 | }
5 |
6 | main {
7 | position: relative;
8 | padding-top: 20px;
9 | }
10 |
11 | .label {
12 | font-weight: bold;
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "es2015",
5 | "outDir": "./dist/",
6 | "sourceMap": true,
7 | "emitDecoratorMetadata": true,
8 | "experimentalDecorators": true,
9 | "removeComments": false,
10 | "noImplicitAny": true,
11 | "lib": ["es2015", "dom"]
12 | },
13 | "exclude": [
14 | "node_modules"
15 | ]
16 | }
--------------------------------------------------------------------------------
/examples/object-oriented/5 - Interfaces and Polymorphism/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 |
3 | module.exports = {
4 | entry: './src/main.ts',
5 | devtool: 'inline-source-map',
6 | module: {
7 | rules: [
8 | {
9 | test: /\.ts?$/,
10 | use: 'ts-loader',
11 | exclude: /node_modules/,
12 | },
13 | ],
14 | },
15 | resolve: {
16 | extensions: [ '.ts' ],
17 | },
18 | output: {
19 | filename: 'bundle.js',
20 | path: path.resolve(__dirname, 'dist'),
21 | },
22 | };
--------------------------------------------------------------------------------
/examples/object-oriented/6 - Putting It All Together/readme.md:
--------------------------------------------------------------------------------
1 | ## Putting It All Together
2 |
3 | Thanks for checking out the `Creating Object-Oriented TypeScript Code` course on Pluralsight!
4 |
5 | This module of the course provides a review of the key topics so there's no code to show.
6 | If you want the final code solution for the course go to the
7 | `object-oriented/solution` directory.
8 |
--------------------------------------------------------------------------------
/examples/object-oriented/solution/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "type": "chrome",
6 | "request": "launch",
7 | "name": "Launch Chrome against localhost",
8 | "url": "http://localhost:3000",
9 | "sourceMaps": true,
10 | "webRoot": "${workspaceRoot}"
11 | },
12 | {
13 | "type": "chrome",
14 | "request": "attach",
15 | "name": "Attach to Chrome",
16 | "port": 9222,
17 | "webRoot": "${workspaceRoot}"
18 | }
19 | ]
20 | }
--------------------------------------------------------------------------------
/examples/object-oriented/solution/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | // Place your settings in this file to overwrite default and user settings.
2 | {
3 | "files.exclude": {
4 | "**/*.js": {
5 | "when": "$(basename).ts"
6 | },
7 | "**/*.js.map": {
8 | "when": "$(basename)"
9 | }
10 | // "examples/**/*.js.map": true,
11 | // "examples/**/*.js": true
12 | }
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/solution/data.json:
--------------------------------------------------------------------------------
1 | {
2 | "checkingAccount": {
3 | "id": 1,
4 | "balance": 500,
5 | "title": "Jane Doe Checking"
6 | },
7 | "savingsAccount": {
8 | "id": 2,
9 | "balance": 1500,
10 | "title": "Jane Doe Savings",
11 | "interestRate": 2.5
12 | }
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/solution/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Bank Accounts
7 |
8 |
9 |
10 |
11 |
12 |
13 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/examples/object-oriented/solution/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "intro-to-typescript",
3 | "version": "1.0.0",
4 | "description": "Introduction to TypeScript",
5 | "scripts": {
6 | "postinstall": "",
7 | "tsc": "tsc",
8 | "tsc:w": "tsc --watch",
9 | "webpack": "npx webpack --mode development",
10 | "webpack:w": "npx webpack --mode development --watch",
11 | "start": "lite-server"
12 | },
13 | "dependencies": {
14 | "lite-server": "^2.6.1"
15 | },
16 | "devDependencies": {
17 | "ts-loader": "^6.2.1",
18 | "tslint": "^5.20.1",
19 | "typescript": "^3.7.2",
20 | "webpack": "^4.41.2",
21 | "webpack-cli": "^3.3.12"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/examples/object-oriented/solution/readme.md:
--------------------------------------------------------------------------------
1 | ## Final Code Solution
2 |
3 | This is the final code solution for the course.
4 |
5 | ### Steps to Run the Code
6 |
7 | 1. Run `npm install` at the command-line from the root of the `solution` directory (where the package.json file lives).
8 | 2. Run `npm run webpack:w` to start the TypeScript build process in a command window. This will compile all of the TypeScript files and generate `.js` and `.map` (for debugging) files. A watcher will also be created to monitor any changes in the .ts files. Leave the command-window open while doing development work.
9 | 3. Run `npm start` in a separate command window. This will launch a local web server and browser.
10 |
11 | **Note:** When you're done running the code press `ctrl+c` in each of the command windows you opened above to stop the running processes.
12 |
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/images/acmebank.afphoto:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DanWahlin/TypeScriptDemos/1786569708632176d5a33faaa40f0dac570b690f/examples/object-oriented/solution/src/images/acmebank.afphoto
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/images/acmebank.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DanWahlin/TypeScriptDemos/1786569708632176d5a33faaa40f0dac570b690f/examples/object-oriented/solution/src/images/acmebank.jpg
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/images/atm.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DanWahlin/TypeScriptDemos/1786569708632176d5a33faaa40f0dac570b690f/examples/object-oriented/solution/src/images/atm.jpg
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/images/checking.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DanWahlin/TypeScriptDemos/1786569708632176d5a33faaa40f0dac570b690f/examples/object-oriented/solution/src/images/checking.jpg
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/images/savings.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DanWahlin/TypeScriptDemos/1786569708632176d5a33faaa40f0dac570b690f/examples/object-oriented/solution/src/images/savings.jpg
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/main.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | var __assign = (this && this.__assign) || function () {
3 | __assign = Object.assign || function(t) {
4 | for (var s, i = 1, n = arguments.length; i < n; i++) {
5 | s = arguments[i];
6 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 | t[p] = s[p];
8 | }
9 | return t;
10 | };
11 | return __assign.apply(this, arguments);
12 | };
13 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15 | return new (P || (P = Promise))(function (resolve, reject) {
16 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19 | step((generator = generator.apply(thisArg, _arguments || [])).next());
20 | });
21 | };
22 | var __generator = (this && this.__generator) || function (thisArg, body) {
23 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25 | function verb(n) { return function (v) { return step([n, v]); }; }
26 | function step(op) {
27 | if (f) throw new TypeError("Generator is already executing.");
28 | while (_) try {
29 | if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30 | if (y = 0, t) op = [op[0] & 2, t.value];
31 | switch (op[0]) {
32 | case 0: case 1: t = op; break;
33 | case 4: _.label++; return { value: op[1], done: false };
34 | case 5: _.label++; y = op[1]; op = [0]; continue;
35 | case 7: op = _.ops.pop(); _.trys.pop(); continue;
36 | default:
37 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41 | if (t[2]) _.ops.pop();
42 | _.trys.pop(); continue;
43 | }
44 | op = body.call(thisArg, _);
45 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47 | }
48 | };
49 | Object.defineProperty(exports, "__esModule", { value: true });
50 | var checking_account_1 = require("./scripts/checking-account");
51 | var savings_account_1 = require("./scripts/savings-account");
52 | var account_list_1 = require("./scripts/account-list");
53 | var renderer_1 = require("./scripts/renderer");
54 | var enums_1 = require("./scripts/enums");
55 | var atm_1 = require("./scripts/atm");
56 | var Main = /** @class */ (function () {
57 | function Main(renderer) {
58 | this.renderer = renderer;
59 | }
60 | Main.prototype.loadAccounts = function () {
61 | return __awaiter(this, void 0, void 0, function () {
62 | var response, data, html;
63 | return __generator(this, function (_a) {
64 | switch (_a.label) {
65 | case 0: return [4 /*yield*/, fetch('/data.json')];
66 | case 1:
67 | response = _a.sent();
68 | return [4 /*yield*/, response.json()];
69 | case 2:
70 | data = _a.sent();
71 | this.checkingAccount = new checking_account_1.CheckingAccount(__assign({}, data.checkingAccount));
72 | this.savingsAccount = new savings_account_1.SavingsAccount(__assign({}, data.savingsAccount));
73 | this.atm = new atm_1.ATM(this.checkingAccount);
74 | html = this.renderAccounts();
75 | this.renderer.render("\n Welcome to Acme Bank!
\n \n
\n Your Accounts:
\n " + html + "\n ");
76 | return [2 /*return*/];
77 | }
78 | });
79 | });
80 | };
81 | Main.prototype.changeView = function (view) {
82 | switch (view) {
83 | case 'checking':
84 | this.currentAccount = this.checkingAccount;
85 | break;
86 | case 'savings':
87 | this.currentAccount = this.savingsAccount;
88 | break;
89 | case 'atm':
90 | this.currentAccount = this.checkingAccount;
91 | this.renderAtm();
92 | return;
93 | }
94 | this.renderAccount(this.currentAccount);
95 | };
96 | Main.prototype.renderAtm = function () {
97 | var html = "\n ATM
\n \n
\n Current Checking Account Balance: $" + this.checkingAccount.balance + "\n
\n $ \n \n \n ";
98 | this.renderer.render(html);
99 | };
100 | Main.prototype.renderAccounts = function () {
101 | var acctsHtml = '';
102 | var accList = new account_list_1.AccountList();
103 | accList.add(this.checkingAccount);
104 | accList.add(this.savingsAccount);
105 | accList.getAccounts().forEach(function (acct, index) {
106 | acctsHtml += acct.title + '
';
107 | });
108 | return acctsHtml;
109 | };
110 | Main.prototype.renderAccount = function (account) {
111 | var accountType = enums_1.AccountType[account.accountType];
112 | var html = "\n " + accountType + " Account
\n \n
\n Owner: " + account.title + "\n
\n Balance: $" + account.balance.toFixed(2) + "\n
\n $ \n \n \n ";
113 | this.renderer.render(html);
114 | };
115 | Main.prototype.depositWithDrawal = function (deposit, atm) {
116 | var amountInput = document.querySelector('#depositWithdrawalAmount');
117 | var amount = +amountInput.value;
118 | var error;
119 | try {
120 | if (deposit) {
121 | if (atm) {
122 | this.atm.deposit(amount);
123 | }
124 | else {
125 | this.currentAccount.deposit(amount);
126 | }
127 | }
128 | else {
129 | if (atm) {
130 | this.atm.withdrawal(amount);
131 | }
132 | else {
133 | this.currentAccount.withdrawal(amount);
134 | }
135 | }
136 | }
137 | catch (e) {
138 | error = e;
139 | }
140 | (atm) ? this.renderAtm() : this.renderAccount(this.currentAccount);
141 | if (error) {
142 | this.renderer.renderError(error.message);
143 | }
144 | };
145 | return Main;
146 | }());
147 | // Create main object and add handlers for it
148 | var renderer = new renderer_1.Renderer(document.querySelector('#viewTemplate'));
149 | var main = new Main(renderer);
150 | main.loadAccounts();
151 | // Quick and easy way to expose a global API that can hook to the Main object
152 | // so that we can get to it from click and events and others.
153 | // Yes, there are other ways but this gets the job done for this demo.
154 | window.main = main;
155 | //# sourceMappingURL=main.js.map
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/main.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"main.js","sourceRoot":"","sources":["main.ts"],"names":[],"mappings":"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"}
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/main.ts:
--------------------------------------------------------------------------------
1 | import { CheckingAccount } from './scripts/checking-account';
2 | import { SavingsAccount } from './scripts/savings-account';
3 | import { AccountList } from './scripts/account-list';
4 | import { BankAccount } from './scripts/bank-account';
5 | import { Renderer } from './scripts/renderer';
6 | import { AccountType } from './scripts/enums';
7 | import { ATM } from './scripts/atm';
8 |
9 | class Main {
10 | checkingAccount: CheckingAccount;
11 | savingsAccount: SavingsAccount;
12 | currentAccount: BankAccount;
13 | atm: ATM;
14 |
15 | constructor(private renderer: Renderer) { }
16 |
17 | async loadAccounts() {
18 | const response = await fetch('/data.json');
19 | const data = await response.json();
20 | this.checkingAccount = new CheckingAccount({ ...data.checkingAccount });
21 | this.savingsAccount = new SavingsAccount({ ...data.savingsAccount });
22 | this.atm = new ATM(this.checkingAccount);
23 |
24 | let html = this.renderAccounts();
25 | this.renderer.render(`
26 | Welcome to Acme Bank!
27 |
28 |
29 | Your Accounts:
30 | ${html}
31 | `);
32 | }
33 |
34 | changeView(view?: string) {
35 | switch (view) {
36 | case 'checking':
37 | this.currentAccount = this.checkingAccount;
38 | break;
39 | case 'savings':
40 | this.currentAccount = this.savingsAccount;
41 | break;
42 | case 'atm':
43 | this.currentAccount = this.checkingAccount;
44 | this.renderAtm();
45 | return;
46 | }
47 | this.renderAccount(this.currentAccount);
48 | }
49 |
50 | renderAtm() {
51 | const html = `
52 | ATM
53 |
54 |
55 | Current Checking Account Balance: $${this.checkingAccount.balance}
56 |
57 | $
58 |
59 |
60 | `;
61 | this.renderer.render(html);
62 | }
63 |
64 | renderAccounts() {
65 | let acctsHtml: string = '';
66 | const accList = new AccountList();
67 | accList.add(this.checkingAccount);
68 | accList.add(this.savingsAccount);
69 |
70 | accList.getAccounts().forEach((acct, index) => {
71 | acctsHtml += acct.title + '
';
72 | });
73 | return acctsHtml;
74 | }
75 |
76 | renderAccount(account: BankAccount) {
77 | const accountType = AccountType[account.accountType];
78 | const html = `
79 | ${accountType} Account
80 |
81 |
82 | Owner: ${account.title}
83 |
84 | Balance: $${account.balance.toFixed(2)}
85 |
86 | $
87 |
88 |
89 | `;
90 | this.renderer.render(html);
91 | }
92 |
93 | depositWithDrawal(deposit: boolean, atm?: boolean) {
94 | let amountInput: HTMLInputElement = document.querySelector('#depositWithdrawalAmount');
95 | let amount = +amountInput.value;
96 | let error;
97 | try {
98 | if (deposit) {
99 | if (atm) {
100 | this.atm.deposit(amount);
101 | }
102 | else {
103 | this.currentAccount.deposit(amount);
104 | }
105 | }
106 | else {
107 | if (atm) {
108 | this.atm.withdrawal(amount);
109 | }
110 | else {
111 | this.currentAccount.withdrawal(amount);
112 | }
113 | }
114 | }
115 | catch (e) {
116 | error = e;
117 | }
118 |
119 | (atm) ? this.renderAtm(): this.renderAccount(this.currentAccount);
120 | if (error) {
121 | this.renderer.renderError(error.message);
122 | }
123 | }
124 | }
125 |
126 | // Create main object and add handlers for it
127 | const renderer = new Renderer(document.querySelector('#viewTemplate'));
128 | const main = new Main(renderer);
129 | main.loadAccounts();
130 |
131 | // Quick and easy way to expose a global API that can hook to the Main object
132 | // so that we can get to it from click and events and others.
133 | // Yes, there are other ways but this gets the job done for this demo.
134 | (window).main = main;
135 |
136 |
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/scripts/account-list.ts:
--------------------------------------------------------------------------------
1 | import { Account } from './interfaces';
2 |
3 | export class AccountList {
4 | _accountList: Account[] = [];
5 |
6 | add(account: Account) {
7 | this._accountList.push(account);
8 | }
9 |
10 | getAccounts(): Account[] {
11 | return this._accountList;
12 | }
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/scripts/atm.ts:
--------------------------------------------------------------------------------
1 | import { DepositWithdrawal, Account } from './interfaces';
2 |
3 | export class ATM implements DepositWithdrawal {
4 |
5 | constructor(private account: Account) { }
6 |
7 | deposit(amount: number) {
8 | this.account.deposit(amount);
9 | }
10 |
11 | withdrawal(amount: number) {
12 | this.account.withdrawal(amount);
13 | }
14 | }
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/scripts/bank-account.ts:
--------------------------------------------------------------------------------
1 | import { Account, AccountInfo, AccountSettings } from './interfaces';
2 | import { Constants } from './constants';
3 | import { AccountType } from './enums';
4 |
5 | export abstract class BankAccount implements Account {
6 | id: number;
7 | title: string;
8 | private _balance = 0;
9 | abstract accountType: AccountType;
10 |
11 | constructor(accountSettings: AccountSettings) {
12 | this.id = accountSettings.id;
13 | this.title = accountSettings.title;
14 | this.balance = accountSettings.balance;
15 | }
16 |
17 | deposit(amount: number) {
18 | this.balance += amount;
19 | }
20 |
21 | withdrawal(amount: number) {
22 | this.balance -= amount;
23 | }
24 |
25 | getAccountInfo() : AccountInfo {
26 | return {
27 | routingNumber: Constants.ROUTING_NUMBER,
28 | bankNumber: Constants.BANK_NUMBER
29 | };
30 | }
31 |
32 | get balance() {
33 | return this._balance;
34 | }
35 |
36 | set balance(val: number) {
37 | if (val >= 0) {
38 | this._balance = val;
39 | }
40 | else {
41 | throw Error('Balance cannot be negative!');
42 | }
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/scripts/checking-account.ts:
--------------------------------------------------------------------------------
1 | import { BankAccount } from './bank-account';
2 | import { AccountType } from './enums';
3 |
4 | export class CheckingAccount extends BankAccount {
5 | accountType = AccountType.Checking;
6 | }
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/scripts/constants.ts:
--------------------------------------------------------------------------------
1 | export class Constants {
2 | static get ROUTING_NUMBER(): string { return '1231A4433Y2'; }
3 | static get BANK_NUMBER(): number { return 100008374; }
4 | }
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/scripts/enums.ts:
--------------------------------------------------------------------------------
1 | export enum AccountType {
2 | Checking,
3 | Savings
4 | }
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/scripts/interfaces.ts:
--------------------------------------------------------------------------------
1 | export interface AccountInfo {
2 | routingNumber: TRouteNumber;
3 | bankNumber: TBankNumber;
4 | }
5 |
6 | export interface DepositWithdrawal {
7 | deposit(amount: number): void;
8 | withdrawal(amount: number): void;
9 | }
10 |
11 | export interface AccountSettings {
12 | id: number;
13 | title: string;
14 | balance : number;
15 | interestRate?: number;
16 | accountInfo?: AccountInfo;
17 | }
18 |
19 | export interface Account extends AccountSettings, DepositWithdrawal { }
20 |
21 |
22 |
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/scripts/renderer.ts:
--------------------------------------------------------------------------------
1 | export class Renderer {
2 | constructor(private viewTemplate: HTMLDivElement) {
3 | this.viewTemplate.innerHTML = `
4 | Welcome to Acme Bank!
5 |
6 |
7 | Your Accounts:
`;
8 | }
9 |
10 | render(html: string) {
11 | this.viewTemplate.innerHTML = html;
12 | }
13 |
14 | renderError(message: string) {
15 | this.viewTemplate.innerHTML += `
${message}
`;
16 | }
17 | }
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/scripts/savings-account.ts:
--------------------------------------------------------------------------------
1 | import { BankAccount } from './bank-account';
2 | import { AccountType } from './enums';
3 | import { AccountSettings } from './interfaces';
4 |
5 |
6 | export class SavingsAccount extends BankAccount {
7 | private _interestRate: number;
8 | accountType = AccountType.Savings;
9 |
10 | constructor(accountSettings: AccountSettings) {
11 | super(accountSettings);
12 | this._interestRate = accountSettings.interestRate;
13 |
14 | // Simulate interest over time
15 | setInterval(() => {
16 | this.addInterest();
17 | }, 60000);
18 | }
19 |
20 | deposit(amount: number) {
21 | let newAmount = amount + (amount * (this._interestRate / 100));
22 | this.balance += newAmount;
23 | }
24 |
25 | private addInterest() {
26 | this.balance = this.balance + (this.balance * (this._interestRate / 100));
27 | }
28 | }
29 |
30 |
--------------------------------------------------------------------------------
/examples/object-oriented/solution/src/styles/styles.css:
--------------------------------------------------------------------------------
1 | html {
2 | overflow-y: scroll;
3 | overflow-x: hidden;
4 | }
5 |
6 | main {
7 | position: relative;
8 | padding-top: 20px;
9 | }
10 |
11 | .label {
12 | font-weight: bold;
13 | }
--------------------------------------------------------------------------------
/examples/object-oriented/solution/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "es2015",
5 | "outDir": "./dist/",
6 | "sourceMap": true,
7 | "emitDecoratorMetadata": true,
8 | "experimentalDecorators": true,
9 | "removeComments": false,
10 | "noImplicitAny": true,
11 | "lib": ["es2015", "dom"]
12 | },
13 | "exclude": [
14 | "node_modules"
15 | ]
16 | }
--------------------------------------------------------------------------------
/examples/object-oriented/solution/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 |
3 | module.exports = {
4 | entry: './src/main.ts',
5 | devtool: 'inline-source-map',
6 | module: {
7 | rules: [
8 | {
9 | test: /\.ts?$/,
10 | use: 'ts-loader',
11 | exclude: /node_modules/,
12 | },
13 | ],
14 | },
15 | resolve: {
16 | extensions: [ '.ts' ],
17 | },
18 | output: {
19 | filename: 'bundle.js',
20 | path: path.resolve(__dirname, 'dist'),
21 | },
22 | };
--------------------------------------------------------------------------------
/examples/optional-default-parameters/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Optional, Default, Rest Parameters
7 |
8 |
9 |
10 |
11 |
12 |
Optional, Default, Rest Parameters
13 |
Enter Your Address
14 |
15 |
16 |
20 |
21 |
Address 2 (optional):
22 |
23 |
24 |
28 |
31 |
32 |
Final Address:
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/examples/optional-default-parameters/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Optional and Default Parameters",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/optional-default-parameters/scripts/optionalDefaultRestParameters.ts:
--------------------------------------------------------------------------------
1 | (function () {
2 |
3 | //Optional parameter
4 | function buildAddressOptional(address1: string, city: string, address2?: string) {
5 | var addr2 = (address2) ? ' Address2: ' + address2 : '';
6 | displayAddress(address1 + addr2 + ', ' + city);
7 | }
8 |
9 | //Default parameter
10 | function buildAddressDefault(address1: string, city: string, address2 = 'N/A') {
11 | displayAddress('Address: ' + address1 + ' Address2: ' + address2 + ' City: ' + city);
12 | }
13 |
14 | //Rest parameters
15 | function buildAddressRest(city: string, ...restOfAddress: string[]) {
16 | var address = '';
17 | restOfAddress.forEach((addr) => address += ' ' + addr);
18 | displayAddress(restOfAddress + ', ' + city);
19 | }
20 |
21 | function displayAddress(msg: string) {
22 | result.innerHTML = msg;
23 | }
24 |
25 | var $ = (id: any) => document.getElementById(id);
26 |
27 | var addressButton: HTMLButtonElement = $('addressButton'),
28 | address: HTMLInputElement = $('address'),
29 | address2: HTMLInputElement = $('address2'),
30 | city: HTMLInputElement = $('city'),
31 | result = $('result');
32 |
33 | //Call function with optional parameter
34 | //addressButton.addEventListener('click',(e) => buildAddressOptional(address.value, city.value));
35 |
36 | //Call function with default parameter
37 | //addressButton.addEventListener('click',(e) => buildAddressDefault(address.value, city.value));
38 |
39 | //Call function with Rest parameters
40 | addressButton.addEventListener('click',(e) => buildAddressRest(city.value, address.value, address2.value));
41 |
42 | } ());
--------------------------------------------------------------------------------
/examples/optional-default-parameters/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/parameter-types/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Defining Parameter Types
7 |
8 |
9 |
10 | Defining Parameter Types
11 | View the developer tools console to see the output.
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/examples/parameter-types/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Parameter Types",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/parameter-types/scripts/parameterTypes.ts:
--------------------------------------------------------------------------------
1 | function add(msg: string, x: number, y: number) {
2 | console.log(msg + (x + y));
3 | }
4 |
5 | add('typed parameters (msg: string, x: number, y: number) = ', 3, 2);
6 |
7 |
--------------------------------------------------------------------------------
/examples/parameter-types/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/examples/scratchpad/demo.js:
--------------------------------------------------------------------------------
1 | var Person = /** @class */ (function () {
2 | function Person(name, age) {
3 | this.name = name;
4 | this.age = age;
5 | }
6 | return Person;
7 | }());
8 | var person = new Person('John', 67);
9 | //# sourceMappingURL=demo.js.map
--------------------------------------------------------------------------------
/examples/scratchpad/demo.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"file":"demo.js","sourceRoot":"","sources":["demo.ts"],"names":[],"mappings":"AAAA;IACI,gBAAmB,IAAY,EACX,GAAW;QADZ,SAAI,GAAJ,IAAI,CAAQ;QACX,QAAG,GAAH,GAAG,CAAQ;IAAI,CAAC;IACxC,aAAC;AAAD,CAAC,AAHD,IAGC;AAED,IAAI,MAAM,GAAG,IAAI,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC"}
--------------------------------------------------------------------------------
/examples/scratchpad/demo.ts:
--------------------------------------------------------------------------------
1 | class Person {
2 | constructor(public name: string,
3 | private age: number) { }
4 | }
5 |
6 | let person = new Person('John', 67);
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/examples/unions-aliases-const-enums/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Union Types, Type Aliases, and Const Enums
7 |
8 |
9 |
10 | Union Types
11 | View the developer tools console to see the output.
12 |
13 | function showTotal(total: number | number[]) {
14 | if (typeof total === 'number') {
15 | console.log('total number union type = ' + total);
16 | }
17 | else {
18 | var sum: number = total.reduce(function (prevVal, currVal, index, array) {
19 | return prevVal + currVal;
20 | });
21 | console.log('total array union type = ' + sum);
22 | }
23 | }
24 |
25 | var values : number[] = [5, 5, 5, 5];
26 | showTotal(values);
27 | showTotal(50);
28 |
29 |
30 | Type Aliases
31 | View the developer tools console to see the output.
32 |
33 | type int = number;
34 | type float = number;
35 | type StringArray = string[];
36 | type NumberArray = number[];
37 |
38 | var x: int = 5;
39 | var lat: float = 120.05;
40 | var names: StringArray = ['Ted', 'Michelle'];
41 | var ages: NumberArray = [35, 55, 83];
42 |
43 | console.log('type alias x : int = ' + x);
44 | console.log('type alias lat : float = ' + lat);
45 | console.log('type alias names : StringArray = ' + names);
46 | console.log('type alias ages : NumberArray = ' + ages);
47 |
48 |
49 | Constant Enums
50 | View the developer tools console to see the output.
51 |
52 | const enum Gender { Male, Female };
53 | enum NonConstGender { Male, Female };
54 |
55 | var gender = Gender.Female;
56 | var nonConstGender = NonConstGender.Male;
57 |
58 | console.log('Gender is ' + gender);
59 | console.log('NonConstGender is ' + nonConstGender);
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/examples/unions-aliases-const-enums/plnkr.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Unions, Aliases and Const Enums",
3 | "files":[
4 | "!**/*.d.ts",
5 | "!**/*.js"
6 | ],
7 | "tags": ["typescript"]
8 | }
9 |
--------------------------------------------------------------------------------
/examples/unions-aliases-const-enums/scripts/constEnums.ts:
--------------------------------------------------------------------------------
1 | enum NonConstGender { Male, Female };
2 | const enum Gender { Male, Female };
3 |
4 | var nonConstGender = NonConstGender.Male;
5 | var gender = Gender.Female;
6 |
7 | console.log('');
8 | console.log('NonConstGender is ' + nonConstGender);
9 | console.log('Gender is ' + gender);
10 |
--------------------------------------------------------------------------------
/examples/unions-aliases-const-enums/scripts/typeAliases.ts:
--------------------------------------------------------------------------------
1 | type int = number;
2 | type float = number;
3 | type StringArray = string[];
4 | type NumberArray = number[];
5 |
6 | var x: int = 5;
7 | var lat: float = 120.05;
8 | var names: StringArray = ['Ted', 'Michelle'];
9 | var ages: NumberArray = [35, 55, 83];
10 |
11 | console.log('');
12 | console.log('type alias x : int = ' + x);
13 | console.log('type alias lat : float = ' + lat);
14 | console.log('type alias names : StringArray = ' + names);
15 | console.log('type alias ages : NumberArray = ' + ages);
--------------------------------------------------------------------------------
/examples/unions-aliases-const-enums/scripts/unionTypes.ts:
--------------------------------------------------------------------------------
1 | function showTotal(total: number | number[]) {
2 | if (typeof total === 'number') {
3 | console.log('total union type = ' + total);
4 | }
5 | else {
6 | var sum: number = total.reduce(function (prevVal, currVal, index, array) {
7 | return prevVal + currVal;
8 | });
9 | console.log('total union type = ' + sum);
10 | }
11 | }
12 |
13 | var values : number[] = [5, 5, 5, 5];
14 | showTotal(values);
15 | showTotal(50);
--------------------------------------------------------------------------------
/examples/unions-aliases-const-enums/styles/app.css:
--------------------------------------------------------------------------------
1 | body {
2 | font-family: 'Segoe UI', sans-serif;
3 | margin: 20px;
4 | }
5 |
6 | span {
7 | font-style: italic;
8 | }
9 |
10 | pre {
11 | font-size: 18px;
12 | }
13 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | TypeScript Demos
5 |
6 |
11 |
12 |
13 | TypeScript Examples
14 |
15 |
33 |
34 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "typescript-examples",
3 | "version": "1.0.0",
4 | "scripts": {
5 | "tsc": "tsc",
6 | "tsc:w": "tsc --watch",
7 | "start": "tsc && concurrently \"tsc -w\" \"lite-server\""
8 | },
9 | "dependencies": {
10 | "systemjs": "0.20.17"
11 | },
12 | "devDependencies": {
13 | "@types/jquery": "3.3.29",
14 | "concurrently": "5.3.0",
15 | "lite-server": "2.6.1",
16 | "typescript": "4.0.3"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # TypeScript Examples
2 |
3 | ## Running the Application
4 |
5 | 1. Install Node.js from http://nodejs.org
6 |
7 | 1. Run `npm install`
8 |
9 | 1. Run `npm start` to compile the TypeScript and start the server
10 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "commonjs",
5 | "moduleResolution": "node",
6 | "sourceMap": true,
7 | "emitDecoratorMetadata": true,
8 | "experimentalDecorators": true,
9 | "removeComments": false,
10 | "noImplicitAny": false,
11 | "suppressImplicitAnyIndexErrors": true,
12 | "lib": ["es2016","dom"]
13 | },
14 | "exclude": [
15 | "node_modules",
16 | "examples/cookbook"
17 | ]
18 | }
--------------------------------------------------------------------------------