Skip to content
This repository has been archived by the owner on Jun 24, 2024. It is now read-only.

Commit

Permalink
Merge pull request #1 from NicolasOmar/first-exercise
Browse files Browse the repository at this point in the history
Typescript | First exercise
  • Loading branch information
NicolasOmar authored Nov 25, 2022
2 parents 0803496 + ddaa51d commit e1b220e
Show file tree
Hide file tree
Showing 10 changed files with 227 additions and 15 deletions.
1 change: 0 additions & 1 deletion 1-base-project/app.js

This file was deleted.

1 change: 0 additions & 1 deletion 1-base-project/app.ts

This file was deleted.

3 changes: 3 additions & 0 deletions 1-base-project/configs/server.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"server": { "baseDir": "./public" }
}
6 changes: 3 additions & 3 deletions 1-base-project/package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"name": "1-base-project",
"version": "0.0.1",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "npm run build && lite-server",
"build": "tsc app.ts"
"start": "lite-server -c configs/server.json",
"build": "tsc public/scripts/app.ts"
},
"devDependencies": {
"lite-server": "^2.6.1"
Expand Down
Binary file added 1-base-project/public/favicon.ico
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Base TS Project | Exercise #1</title>
<script defer src="./app.js"></script>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<script defer src="./scripts/app.js"></script>
</head>
<body>

Expand Down
74 changes: 74 additions & 0 deletions 1-base-project/public/scripts/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
var testAdd = function (number1, number2, showResult) {
if (showResult === void 0) { showResult = false; }
var fnResult = number1 + number2;
showResult && console.warn(fnResult);
return fnResult;
};
var numbers = [10, 3];
testAdd(numbers[0], numbers[1], true);
var Role;
(function (Role) {
Role[Role["ADMIN"] = 0] = "ADMIN";
Role[Role["USER"] = 1] = "USER";
Role[Role["AUTHOR"] = 2] = "AUTHOR";
})(Role || (Role = {}));
var person = {
age: 15,
name: 'Test person',
hobbies: ['Sports', 'Arts'],
roles: [0, Role.ADMIN]
};
for (var _i = 0, _a = person.hobbies; _i < _a.length; _i++) {
var hobby = _a[_i];
console.warn("OBJECTS, ARRAYS & TUPLE: ".concat(person.name, " likes ").concat(hobby.toLocaleUpperCase()));
}
// UNION TYPES, you can set more that one specific type to handle different kind of data
var combineData = function (input1, input2, resultConversion) { return resultConversion === 'as-number' ? +input1 + +input2 : "".concat(input1.toString()).concat(input2.toString()); };
console.warn('LITERAL & UNION TYPES', combineData(15, 33, 'as-number'), combineData('500', '1', 'as-number'), combineData('Maria', 'Marta', 'as-text'));
// FUNCTION RETURN TYPE, after setting the arguments, you can add a specific return type to avoid type inference
var testAddWithType = function (n1, n2) { return n1 + n2; };
// VOID TYPE is used when the function doesnt return anything
var printResult = function (num) { return console.info('Printing result: ', num); };
printResult(testAddWithType(1, 3)),
printResult(testAddWithType(2, 3)),
printResult(testAddWithType(3, 3));
console.info('VOID TYPE', printResult(testAddWithType(1, 3)), printResult(testAddWithType(2, 3)), printResult(testAddWithType(3, 3)));
// If you try to return a undefined type value, you must indicate a return statement without anything else
// BUT, is preffered that your functions return a void value instead to avoid writing the empty return statement
var returnUndefined = function () { return; };
console.info('UNDEFINED TYPE', returnUndefined(), returnUndefined(), returnUndefined());
// FUNCTION TYPE is used to return another function
var returnFunction;
// In the following cases, you return an empty function and a functions without been executed
returnFunction = function () { };
returnFunction = function () { };
returnFunction = returnUndefined;
// Here the function needs a specific type of function which will recieve two numbers and return another number
var returnNumberFunction;
var addNumbers = function (n1, n2) { return (n1 + n2); };
returnNumberFunction = addNumbers;
// On this case, you using a function callback as a parameter wich will recieve a result and handle it without care about what is going to return
var addAndHandle = function (n1, n2, cb) { return cb(n1 + n2); };
addAndHandle(3, 5, printResult);
// UNKNOWN TYPE, we dont know yet what the user is going to input
var userInput;
var userName;
userInput = 5;
userInput = '5';
userInput = null;
/* Unknown type is used to check other variables types before assign its value.
* If a string variable tries to be assigned to a unknown one, it will break the compilation
* unless you check its typeof before
* Is a better alternative than use any (for previous type checking)
*/
if (typeof userInput === 'string') {
userName = userInput;
}
/* VOID/NEVER TYPE is used when you want a function does not retun any value
* It can be used for special cases as error handling, because it does not return
* a value, it just throws an error
*/
var generateError = function (message, code) {
throw { message: message, errorCode: code };
};
generateError('An error ocurred!', 500);
119 changes: 119 additions & 0 deletions 1-base-project/public/scripts/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
const testAdd = (number1: number, number2: number, showResult: boolean = false) => {
const fnResult = number1 + number2
showResult && console.warn(fnResult)
return fnResult
}

const numbers = [10, 3]

testAdd(numbers[0], numbers[1], true)

enum Role {
ADMIN,
USER,
AUTHOR
}

const person: {
age: number,
name: string,
hobbies: string[],
// TUPLE, only permits the specified amount of items with its asigned types
roles: [number, Role]
} = {
age: 15,
name: 'Test person',
hobbies: ['Sports', 'Arts'],
roles: [0, Role.ADMIN]
}

for (const hobby of person.hobbies) {
console.warn(`OBJECTS, ARRAYS & TUPLE: ${person.name} likes ${hobby.toLocaleUpperCase()}`)
}

// You can create CUSTOM/LITERAL TYPES to save unnecesary duplication
type NumberString = number | string
type ConversionType = 'as-number' | 'as-text'

// UNION TYPES, you can set more that one specific type to handle different kind of data
const combineData = (
input1: NumberString,
input2: NumberString,
resultConversion: ConversionType
) => resultConversion === 'as-number' ? +input1 + +input2 : `${input1.toString()}${input2.toString()}`

console.warn(
'LITERAL & UNION TYPES',
combineData(15, 33, 'as-number'),
combineData('500', '1', 'as-number'),
combineData('Maria', 'Marta', 'as-text')
)

// FUNCTION RETURN TYPE, after setting the arguments, you can add a specific return type to avoid type inference
const testAddWithType = (n1: number, n2: number): number => n1 + n2

// VOID TYPE is used when the function doesnt return anything
const printResult = (num: number): void => console.info('Printing result: ', num)

printResult(testAddWithType(1, 3)),
printResult(testAddWithType(2, 3)),
printResult(testAddWithType(3, 3))

console.info(
'VOID TYPE',
printResult(testAddWithType(1, 3)),
printResult(testAddWithType(2, 3)),
printResult(testAddWithType(3, 3))
)

// If you try to return a undefined type value, you must indicate a return statement without anything else
// BUT, is preffered that your functions return a void value instead to avoid writing the empty return statement
const returnUndefined = (): undefined => { return }

console.info(
'UNDEFINED TYPE',
returnUndefined(),
returnUndefined(),
returnUndefined()
)

// FUNCTION TYPE is used to return another function
let returnFunction: Function
// In the following cases, you return an empty function and a functions without been executed
returnFunction = () => {}
returnFunction = function () {}
returnFunction = returnUndefined

// Here the function needs a specific type of function which will recieve two numbers and return another number
let returnNumberFunction: (a: number, b: number) => number
const addNumbers = (n1: number, n2: number) => (n1 + n2)
returnNumberFunction = addNumbers

// On this case, you using a function callback as a parameter wich will recieve a result and handle it without care about what is going to return
let addAndHandle = (n1: number, n2: number, cb: (n3: number) => void) => cb(n1 + n2)
addAndHandle(3, 5, printResult)

// UNKNOWN TYPE, we dont know yet what the user is going to input
let userInput: unknown
let userName: string

userInput = 5
userInput = '5'
userInput = null
/* Unknown type is used to check other variables types before assign its value.
* If a string variable tries to be assigned to a unknown one, it will break the compilation
* unless you check its typeof before
* Is a better alternative than use any (for previous type checking)
*/
if (typeof userInput === 'string') {
userName = userInput
}

/* VOID/NEVER TYPE is used when you want a function does not retun any value
* It can be used for special cases as error handling, because it does not return
* a value, it just throws an error
*/
const generateError = (message: string, code: number): void | never => {
throw { message, errorCode: code }
}
generateError('An error ocurred!', 500)
23 changes: 20 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,30 @@ Repository created to record my practice learning React with exercises based on
- [Node](https://nodejs.org/en/download/) v16.13.2 or above

## Setup
TBD
After cloning the repo, go to the created folder and install the node packages.
```sh
git clone https://github.com/NicolasOmar/typescript-practice.git
cd typescript-practice
npm run setup-all
```
`setup-all` is the command to install all the projects, but if you want to do it one by one, you can change that last line for one of the following:
| App Setup | Command |
| ------ | ------ |
| All | `npm run setup-all` |
| Base project | `npm run setup-base-project` |

## How to run it
TBD
To run any specific exercise, execute the following command in the project´s folder:
```sh
npm start
```

## Repo Structure & what i learned in each exercise
- TBD
- Base project (`1-base-project` folder)
- Create, code and compile a `.ts` file into javascript
- Understanding of `Core Types` like `number`, `string`, `boolean`, `array` and `object`
- Understanding of `Tuples`, `Enums`, `Union` and `Literal/Custom` Types
- Understanding of `void`, `undefined`, `unknown` and `never` Types

## Version (currently ![Typescript practice version](https://img.shields.io/github/package-json/v/nicolasomar/typescript-practice?color=success&label=%20&style=flat-square))
| Number | Meaning |
Expand Down
12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
{
"name": "typescript-practice",
"version": "0.0.0",
"version": "0.0.1",
"description": "Repository created to record my practice learning Typescript",
"main": "index.js",
"scripts": {
"setup-base-project": "cd ./1-base-project && npm i",
"setup-all": "npm i -g typescript && npm run setup-base-project"
},
"repository": {
"type": "git",
"url": "git+https://github.com/NicolasOmar/typescript-practice.git"
Expand All @@ -16,5 +12,9 @@
"bugs": {
"url": "https://github.com/NicolasOmar/typescript-practice/issues"
},
"homepage": "https://github.com/NicolasOmar/typescript-practice#readme"
"homepage": "https://github.com/NicolasOmar/typescript-practice#readme",
"scripts": {
"setup-base-project": "cd ./1-base-project && npm i",
"setup-all": "npm i -g typescript && npm run setup-base-project"
}
}

0 comments on commit e1b220e

Please sign in to comment.