fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,13 @@
---
title: Any Type
---
# Any Type
The Any type instructs Typescript to suspend type checking for the specified variables. Useful when working with dynamic content for which you don't know the type, and for transitioning your codebase for Javascript to Typescript in pieces. You can use Javascript's implicit typing with variables declared with a type of Any.
```typescript
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;
```

View File

@ -0,0 +1,53 @@
---
title: Array Type
---
# Array Type
You have full access to arrays in TypeScript.
Arrays can be written two different ways in TypeScript:
__DataType[]__
DataType followed by square brackets `[]`
```typescript
let names: string[] = ['Javier', 'Emma', 'John', 'Sophia', 'Emma'];
```
__Array<DataType>__
`Array` followed by <DataType>
```typescript
let names: Array<string> = ['Javier', 'Emma', 'John', 'Sophia', 'Emma'];
```
## Built-in methods
In Typescript's Array type you can use some built-in functions. Each type has common and unique methods.
Below you can read about the most used ones of the array type's methods. In the example, we will use the array declaration from above.
### pop()
Removes the last element from an array and returns with it.
```typescript
var element = names.pop();
//element = Emma
var element2 = names.pop();
//element2 = Sophia
```
### push()
Adds one or more element to the end of the array and returns with the new length of the array.
```typescript
var length = names.push('Tobias');
// names[] = ['Javier', 'Emma', 'John', 'Sophia', 'Emma', 'Tobias']
// lenght = 6
var length2 = names.push('Jack','Lily');
// names[] = ['Javier', 'Emma', 'John', 'Sophia', 'Emma', 'Tobias','Jack','Lily']
// lenght2 = 8
```
### reverse()
Reverses the order of the array and returns with it
```typescript
var reverseNames = names.reverse();
//reverseNames = ['Emma','Sophia','John','Emma','Javier']
```
[More methods and description at TutorialsPoint](https://www.tutorialspoint.com/typescript/typescript_arrays.htm)

View File

@ -0,0 +1,11 @@
---
title: Boolean Type
---
# Boolean Type
`boolean` is your basic JavaScript true/false value.
```typescript
let isDone: boolean = false;
```

View File

@ -0,0 +1,28 @@
---
title: Enums
---
## Enums
Developers can use `Enums` to define a set of named constants.
There are two types of `Enums`
1. numeric
1. string-based
```typescript
// numeric enum
enum NumericEnum {
numeric1 = 1,
numeric2,
numeric3,
numeric4,
}
// string based enum
enum StringBasedEnum {
Programming = "is fun",
Pizza = "is good"
}
```

View File

@ -0,0 +1,17 @@
---
title: For..Of Loop
---
# For..Of Loop
`for..of` loop is a special loop in TypeScript which you can use to iterate through values of an array.
```typescript
let fruits = ['Apple', 'Banana', 'Orange'];
for (let fruit of fruits) {
console.log(fruit);
}
```
The output you will get from the code above will be "Apple", "Banana", and "Orange". Since this loop type does not iterate through indices, you will not get "0", "1", and "2".

View File

@ -0,0 +1,73 @@
---
title: Generics
---
## Generics
Developers can use `Generics` to specify type constrains for classes, instance members, static members, and functions.
### What do Generics do?
Essentially, they serve as placeholders for types so that a component can be used in multiple places across your application by accommodating different types.
### What problem do Generics solve?
Let's say you wanted to ensure that the input and return values for a function are of the same type, this is where generics come in.
##### Functions
```typescript
function printMessage(arg: any): any {
return arg;
}
// typescript won't complain because the argument type and return type aren't being typed properly
const myMessage: string = printMessage(1);
```
As you can see from above, passing in `any` for the argument type in the function, as well as the return type, is not ideal as type information is lost in the process.
```typescript
// updated example
function printMessage<T>(arg: T): T {
return arg;
}
// typescript complains because the variable type and the return type of the function don't match
const myMessage: string = printMessage(1);
// resolve the issue by making sure both types match each other
const myMessage: number = printMessage(1);
```
Including `<T>` with the function tells TypeScript that it is a generic, and passing that around as a reference will make TypeScript aware that the the values associated with it are of the same type.
##### Classes
```typescript
class Person {
fullName: string;
constructor(fullName: string) {
this.fullName = fullName;
}
getFullName() {
return 'My name is ' + this.fullName;
}
}
class Guest extends Person {};
let guest = new Guest('abc');
function getUser<T>(user: T): T {
return user;
}
// foo will be of type 'guest' because it's being passed in as the argument
const foo = getUser(guest);
```

View File

@ -0,0 +1,27 @@
---
title: Getters & Setters
---
# Getters & Setters
Typescript also supports `get` and `set` property. Get and Set Properties are actually called Accessors. Accessors of a property contains executable statements associated with getting (reading) or setting (writing) the property. The declarations can contain get accessor or set accessor or both.
```typescript
class User {
private _fullName: string = '';
get fullName() {
return this._fullName;
}
set fullName(name) {
this._fullName = name;
}
}
let user = new User();
user.fullName = 'John Doe';
console.log(user.fullName);
```

View File

@ -0,0 +1,58 @@
---
title: TypeScript
---
## TypeScript
### Overview
![TypeScript](https://i.imgur.com/uRLunzU.png)
So as you are most likely aware, JavaScript is expanding its footprint everyday and it is both overwhelming and amazing what you can do with the language nowadays.
However, as more large-scale projects start to use JavaScript, the process of making the code easier to write and more maintainable becomes more and more difficult.
This is a problem Microsoft recognized early on and they came up with the solution of TypeScript and released the first version approximately on October 1st, 2012.
You can learn more about the syntax differences at [`TypeScript`](./) > [`JavaScript vs TypeScript`](./javascript-vs-typescript).
![Key Features](https://i.imgur.com/pZij95O.jpg)
In essence, TypeScript is trying to help JavaScript reach new heights and become very scalable and can be highlighting by the following features:
- free and open-source programming language developed and maintained by Microsoft
- strict syntactical super-set of JavaScript that compiles to plain JavaScript
- eases development of large scale applications written in JavaScript
- extends JavaScript by adding static types, classes, modules, interfaces and generics
**🎉 FUN FACT** TypeScript turned 5 years old on October 1st, 2017.
### Version
Latest stable version available is [TypeScript 3.1](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html).
### Installation
To learn more about installation, see [`TypeScript`](./) > [`Installation`](./installation).
### Linter
To learn more about using a linter with TypeScript, check out [`TypeScript`](./) > [`Linter`](./linter).
### Playground
![Playground](https://i.imgur.com/vlV7ZFr.png)
If you want to try out TypeScript without installing it, visit the <a href='http://www.typescriptlang.org/play/index.html' target='_blank' rel='nofollow'>TypeScript Playground</a>.
The Playground has built-in auto completion and the ability to directly see the emitted JavaScript.
### Other Resources
To learn more about installation, see the [Installation Appendix](./src/articles/typescript/appendix-installation/index.md).
In case you need just a type checker and don't want to compile your programm, read about <a href='https://facebook.github.io/flux/' target='_blank' rel='nofollow'>Flux</a>.
- <a href='http://www.typescriptlang.org/samples/index.html' target='_blank' rel='nofollow'>Quick Start</a>
- <a href='http://www.typescriptlang.org/docs/home.html' target='_blank' rel='nofollow'>Documentation</a>
- <a href='https://github.com/Microsoft/TypeScript' target='_blank' rel='nofollow'>Source Code</a>
- <a href="https://www.tutorialspoint.com/typescript/" target="_blank">TutorialsPoint</a>

View File

@ -0,0 +1,87 @@
---
title: Installation
---
## Installation
![Installation](https://i.imgur.com/9ILjA1q.jpg)
To get started yourself, the two things you will need are the TypeScript compiler and a editor that supports TypeScript.
In the above screenshot, I'm installing both the compiler and <a href='https://github.com/palantir/tslint' target='_blank' rel='nofollow'>TSLint</a> (which is similar to <a href='https://eslint.org/' target='_blank' rel='nofollow'>ESLint</a>) using `npm` in <a href='https://code.visualstudio.com/' target='_blank' rel='nofollow'>Visual Studio Code</a>s integrated terminal.
### Installing TypeScript
This command will install the TypeScript package as a dependency in your project using <a href='https://www.npmjs.com/' target='_blank' rel='nofollow'>`npm`</a> which is a popular package manager.
```bash
npm i typescript
```
*To Note* There are <a href='https://docs.npmjs.com/cli/install' target='_blank' rel='nofollow'>several options</a> that `npm` provides depending on where you want TypeScript installed.
- `npm i -g typescript` to globally install the TypeScript package
- `npm i -D typescript` to install the TypeScript package as a dev dependency
### TSLint
See how to setup linting options for TypeScript at [TypeScript](./) > [Linter](./linter) within the **freeCodeCamp Guide**.
### Compiling a single file down to JavaScript
```bash
tsc multiplication.ts
```
*To Note* You can configure this TypeScript compilation process as a custom npm script in your `package.json`.
### Configuration Options
```bash
touch tsconfig.json
```
Theres also the option to create a <a href='https://www.typescriptlang.org/docs/handbook/tsconfig-json.html' target='_blank' rel='nofollow'>`tsconfig.json`</a> file that specifies the root files and compiler options.
Within your <a href='https://www.typescriptlang.org/docs/handbook/tsconfig-json.html' target='_blank' rel='nofollow'>`tsconfig.json`</a> file, for example, you could specify that you want TypeScript to compile down to ES5 instead of ES6.
### Quick Example
![Multiplication](https://i.imgur.com/V5nP3xj.jpg)
In the screenshot above, you can see two files - `multiplication.js` and `multiplication.ts`.
This program just prints out the product of two numbers Ive pre-defined.
> `multiplication.ts`
```typescript
let a: number = 10;
let b: number = 2;
function showProduct(first: number, second: number): void {
console.info("Mathematical! The result is " + first * second + ".");
}
showProduct(a, b);
// Mathematical! The result is 20.
```
Once I've finished creating `multiplication.ts`, I can compile it down to JavaScript using the `tsc` command which stands for TypeScript compile.
> `multiplication.js`
```javascript
var a = 10;
var b = 2;
function showProduct(first, second) {
console.info("Mathematical! The result is " + first * second + ".");
}
showProduct(a, b);
// Mathematical! The result is 20.
```
Bam - I just successfully compiled TypeScript to JavaScript!

View File

@ -0,0 +1,29 @@
---
title: Interfaces
---
# Interfaces
One of TypeScripts core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, `interfaces` fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.
```typescript
interface User = {
firstName: string;
lastName: string;
}
function printUserInfo(user: User) {
console.log(user.firstName);
}
let myObj = {firstName: 'John', lastName: 'Doe'}
printUserInfo(myObj);
```
Interfaces can contain optional parameters
```typescript
interface User = {
email?: string;
}
```

View File

@ -0,0 +1,18 @@
---
title: JavaScript vs TypeScript
---
## JavaScript vs TypeScript
![Where's Waldo](https://i.imgur.com/DznuAou.jpg)
Okay so now that we have a general sense of what TypeScript is, lets play a quick game of **Wheres Waldo**.
In the above screenshot, you can spot the differences between `JavaScript` & `TypeScript` in this very simple multiplication program that just prints out the product of two numbers Ive pre-defined.
### What are those differences though? 🤔️
They're **types**!
So `JavaScript` has dynamic typing in that a variable declared as a number can be turned into a string where as `TypeScript` has static typing meaning you declare beforehand what type of value the variable will hold and it doesnt change.
In that `multiplication.ts` file, Im declaring all these variables to be numbers so they cannot be changed to something else.

View File

@ -0,0 +1,22 @@
---
title: Linter
---
## Linter
![TSLint](https://2.bp.blogspot.com/-w7oeP1geosE/V82a740bTbI/AAAAAAAAAu4/-zJxZsmmH6garbdmUplX0n5Yz5zDsvcVQCLcB/s1600/tslint.png)
A <a href='https://www.wikiwand.com/en/Lint_(software' target='_blank' rel='nofollow'>linter</a> is defined as a tool that detects and flags errors in programming languages, including stylistic errors.
For TypeScript, <a href='http://palantir.github.io/tslint' target='_blank' rel='nofollow'>TSLint</a> is the most popular linter option.
TSLint is an extensible static analysis tool that checks TypeScript code for readability, maintainability, and functionality errors.
It is widely supported across modern editors & build systems and can be customized with your own lint rules, configurations, and formatters.
### Installing TSLint
This command will globally install the `TSLint` package using `npm`, a popular package manager.
```bash
npm i -g tslint
```

View File

@ -0,0 +1,26 @@
---
title: Never Type
---
# Never Type
The `never` type represents the type of values that never occur. For instance, `never` is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns; Variables also acquire the type `never` when narrowed by `any` type guards that can never be true.
The `never` type is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, `never` (except never itself). Even any isnt assignable to never.
```typescript
// Function returning never must have unreachable end point
function error(message: string): never {
throw new Error(message);
}
// Inferred return type is never
function fail() {
return error("Something failed");
}
// Function returning never must have unreachable end point
function infiniteLoop(): never {
while (true) {
}
}
```

View File

@ -0,0 +1,18 @@
---
title: Null Type
---
## Null Type
In TypeScript, null type has the values null. Null is valid values of every type.
```ts
let u: null = null;
```
When using --strictNullChecks flag, null is only assignable to void and their type.
```ts
let s = "foo";
s = null; // error, 'null' is not assignable to 'string'
let sn: string | null = "bar";
sn = null; // ok
```

View File

@ -0,0 +1,15 @@
---
title: Number Type
---
# Number Type
All numbers in TypeScript are floating point values.
TypeScript supports binary and octal literal values from ES6.
```typescript
let decimal: number = 7;
let hex: number = 0xf00d;
let binary: number = 0b0110;
let octal: number = 0o531;
```

View File

@ -0,0 +1,52 @@
---
title: String Type
---
# String Type
Strings can be written with `''` single quotation marks or `""` double quotation marks.
Be consistent with your code and choose a style.
```typescript
let dog: string = 'Fido';
let activity: string = "Playing Outside";
```
Strings can be written using template literals:
```typescript
let greeting: string = `Hello, ${firstName} ${lastName}, thank you for attending the ${eventName} event.`;
```
## Built-in methods
In Typescript's type you can use some built-in functions. Each type has common and unique methods.
Below you can read about the most used ones of the string type's methods.
### split('separator', limit)
With split function, you can split your string at a specified separator. You can set a limit number, thats says how many splits have to do.
The splitted string returns in an array type.
```typescript
let names: string = 'Sarah,Lily,John,Paula,Harvey';
let array: string[] = names.split(',');
//array = ['Sarah','Lily','John','Paula','Harvey']
let array2: string[] = names.split(',',2);
//array2 = ['Sarah','Lily']
```
### substr(startAt,length)
This method return with a substring, which stars at the `startAt` character of original string, and it's length is `length`.
```typescript
let names: string = 'Harvey Specter';
let substr: string = names.substr(3,10);
//substr = 'rvey Spect'
```
### substring(startAt,endAt)
This method is similar to substr(), but has different parameters. The second paramter is also an index about the original string, not a length number.
```typescript
let names: string = 'Harvey Specter';
let substring: string = names.substring(3,10);
//substring = 'rvey Spe'
```
[More methods and description at TutorialsPoint](https://www.tutorialspoint.com/typescript/typescript_strings.htm)

View File

@ -0,0 +1,66 @@
---
title: Tuple Type
---
# Tuple Type
Express an array in which a fixed number of elements of types is known, but not the same.
```typescript
let arr: [string, number];
// This is correct
arr = ['Hello', 7];
//This is incorrect
arr = [7, 'Hello'];
```
When accessing an element outside the known indices, it will use a union type:
```typescript
arr[3] = 'World!'
// OK, 'string' can be assigned to 'string | number'
// Error, 'boolean' is not a 'string | number'
arr[5] = false;
// Error, 'boolean' is not a 'string | number'
```
## Properties
In Typescript's type you can have some buit-in properties. Forexample length or some other unique each types.
### length
This property said, how many element has it's element.
```typescript
let tuple = []; //you can initialize it after the declaration too, not just the method above
tuple[0] = 10;
tuple[1] = 'Mike';
let number = tuple.length;
//number = 2;
```
## Built-in methods
In Typescript's type you can use some built-in functions. Each type has common and unique methods.
Below you can read about the most used ones of the tuple type's methods.
### pop()
Removes the last element from a tuple.
```typescript
var tuple = [10,'Emma',11,'Lily',12,'Mike Ross'];
tuple.pop();
//tuple = [10,'Emma',11,'Lily',12,]
//We popped 'Mike Ross' from the tuple
```
### push()
Adds element to the end of the tuple.
```typescript
var tuple = [10,'Emma',11,'Lily',12,'Mike Ross'];
tuple.push('Rachel Zane');
//tuple = [10,'Emma',11,'Lily',12,'Mike Ross','Rachel Zane']
```
[More info about tuples on TutorialsPoint](https://www.tutorialspoint.com/typescript/typescript_tuples.htm)

View File

@ -0,0 +1,31 @@
---
title: Undefined Type
---
## Undefined Type
In TypeScript, same with null type, undefined type has the values undefined. Undefined is valid values of every type.
```ts
let u: undefined = undefined;
```
When using `--strictNullChecks` flag, undefined is only assignable to void and their type.
```ts
let s = "foo";
s = null; // error, 'null' is not assignable to 'string'
let sn: string | null = "bar";
sn = null; // ok
sn = undefined; // error, 'undefined' is not assignable to 'string | null'
```
With `--strictNullChecks`, an optional parameter automatically adds `| undefined`:
```ts
function f(x: number, y?: number) {
return x + (y || 0);
}
f(1, 2);
f(1);
f(1, undefined);
f(1, null); // error, 'null' is not assignable to 'number | undefined'
```

View File

@ -0,0 +1,14 @@
---
title: Void Type
---
# Void Type
Should not be used for variables, use `null` or `undefined`.
However, use it for functions that do not return a value.
```typescript
const greeting(): void {
alert('Hello, and Welcome to My Webpage!');
}
```