16 |
17 |
18 |
--------------------------------------------------------------------------------
/04-typescript-classes-and-functions/final/src/app.ts:
--------------------------------------------------------------------------------
1 | /***************************************************
2 | * ******LECTURE 37: CREATING & USING CLASS*********
3 | ***************************************************/
4 | /*class User{
5 | firstname: string;
6 | lastname: string;
7 | age: number;
8 | gender: string;
9 |
10 | constructor(fn: string, ln: string, a: number, g: string){
11 | this.firstname = fn;
12 | this.lastname = ln;
13 | this.age = a;
14 | this.gender = g;
15 | }
16 |
17 | greetuser(salutation: string){
18 | const msg = 'Hello ' + salutation+'. ' + this.firstname + ' ' + this.lastname;
19 | console.log(msg)
20 | }
21 | }
22 |
23 | const user1 = new User('john', 'smith', 28, 'male');
24 | const user2 = new User('merry', 'jane', 32, 'female');
25 | const user3 = new User('mark', 'vought', 29, 'male');
26 |
27 | user1.greetuser('Mr');
28 | user2.greetuser('Mrs');
29 |
30 | // console.log(user1);
31 | // console.log(user2);
32 | // console.log(user3);*/
33 |
34 |
35 |
36 | /***************************************************
37 | * *********LECTURE 39: ACCESS MODIFIERS************
38 | ***************************************************/
39 |
40 |
41 | /*class Employee{
42 | constructor(public empName: string, private salary: number, public baseLocation: string, public isEligible: boolean, private hikePercent: number, public readonly empId: number){
43 | }
44 |
45 | public getSalary(){
46 | if(this.isEligible){
47 | return this.getNewsalary()
48 | }
49 | return this.salary;
50 | }
51 |
52 | private getNewsalary(){
53 | return this.salary + this.salary * this.hikePercent / 100;
54 | }
55 | }
56 |
57 | const employee = new Employee('john smith', 10000, 'london', true, 20, 101);
58 | console.log(employee.getSalary());
59 | employee.empId = 200;
60 | console.log(employee.empId)*/
61 |
62 |
63 |
64 | /***************************************************
65 | * *********LECTURE 32: INHERITANCE*****************
66 | ***************************************************/
67 | /*class Person{
68 | name: string;
69 | protected dob: string;
70 | gender: string;
71 |
72 | constructor(name: string, dob: string, gender: string){
73 | this.name = name;
74 | this.dob = dob;
75 | this.gender = gender;
76 | }
77 |
78 | calculateAge(){
79 | console.log('Calculate Age of Person called');
80 | return new Date().getFullYear() - new Date(this.dob).getFullYear();
81 | }
82 | }
83 |
84 | class Employee extends Person{
85 | salary: number;
86 | bonus: number;
87 |
88 | constructor(n: string, dob: string, gen: string, salary: number, bonus: number){
89 | super(n, dob, gen);
90 | this.salary = salary;
91 | this.bonus = bonus;
92 | }
93 |
94 | getSalary(){
95 | return this.salary + this.bonus;
96 | }
97 |
98 | calculateAge(): number {
99 | console.log('Calculate Age of Employee called');
100 | return 2024 - new Date(this.dob).getFullYear();
101 | }
102 | }
103 |
104 | const emp = new Employee('john', '08-30-1991', 'male', 10000, 2000);
105 | console.log(emp.calculateAge());*/
106 |
107 |
108 | /***************************************************
109 | * *********LECTURE 44: GETTER & SETTER*************
110 | ***************************************************/
111 |
112 | /*class Person{
113 | public name: string;
114 | private _age: number | null = null;
115 |
116 | get age(){
117 | if(this._age != null){
118 | return this._age;
119 | }
120 | throw new Error('Age is not defined for person: ' + this.name)
121 |
122 | }
123 |
124 | set age(value: number){
125 | if(value > 0)
126 | this._age = value;
127 | else
128 | throw new Error('Age cannot be a negative value.')
129 | }
130 |
131 | constructor(name: string){
132 | this.name = name;
133 | }
134 | }
135 |
136 | const person = new Person('john');
137 | person.age = -10;
138 | console.log(person.age);
139 |
140 | class Circle{
141 | private _radius: number;
142 |
143 | get radius() {
144 | return this._radius;
145 | }
146 |
147 | set radius(value: number) {
148 | this._radius = value;
149 | }
150 |
151 | get diameter(){
152 | return this._radius * 2;
153 | }
154 |
155 | set diameter(value: number){
156 | this._radius = value / 2;
157 | }
158 | }*/
159 |
160 |
161 | /***************************************************
162 | * ****LECTURE 45: STATIC METHODS & PROPERTIES******
163 | ***************************************************/
164 | /*class Employee{
165 | public firstname: string;
166 | public lastname: string;
167 | public static count: number = 0;
168 |
169 | constructor(firstname: string, lastname: string){
170 | this.firstname = firstname;
171 | this.lastname = lastname;
172 | Employee.count++;
173 | }
174 |
175 | static sayHello(){
176 | return 'Hi There!';
177 | }
178 | }
179 |
180 | const emp1 = new Employee('john', 'smith');
181 | console.log(Employee.count);
182 |
183 | const emp2 = new Employee('john', 'smith');
184 | console.log(Employee.count);
185 |
186 | const emp3 = new Employee('john', 'smith');
187 | console.log(Employee.count);
188 |
189 | console.log(Employee.sayHello());*/
190 |
191 |
192 |
193 | /***************************************************
194 | * ****LECTURE 45: STATIC METHODS & PROPERTIES******
195 | ***************************************************/
196 | /*abstract class Employee{
197 | public firstname: string;
198 | public lastname: string;
199 |
200 | abstract getSalary(): number;
201 |
202 | constructor(fn: string, ln: string){
203 | this.firstname = fn;
204 | this.lastname = ln;
205 | }
206 | }
207 |
208 | class PermanentEmployee extends Employee{
209 | monthlySalary: number;
210 | constructor(fn: string, ln: string, salary: number){
211 | super(fn, ln);
212 | this.monthlySalary = salary;
213 | }
214 |
215 | getSalary(): number {
216 | return this.monthlySalary * 12;
217 | }
218 | }
219 |
220 | class ContractEmployee extends Employee{
221 | hourlySalary: number;
222 |
223 | constructor(fn: string, ln: string, salary: number){
224 | super(fn, ln);
225 | this.hourlySalary = salary;
226 | }
227 |
228 | getSalary(): number {
229 | return this.hourlySalary * 9 * 365;
230 | }
231 | }
232 |
233 | const emp1 = new PermanentEmployee('john', 'smith', 1000);
234 | console.log(emp1.getSalary());
235 |
236 | const emp2 = new ContractEmployee('mark', 'vought', 10);
237 | console.log(emp2.getSalary());*/
238 |
239 |
240 | /***************************************************
241 | * *******LECTURE 46: PRIVATE CONSTRUCTOR***********
242 | ***************************************************/
243 | /*class Person{
244 | private static _instance: Person;
245 |
246 | private constructor(){
247 |
248 | }
249 |
250 | static getInstance(){
251 | if(Person._instance){
252 | return Person._instance;
253 | }
254 | Person._instance = new Person();
255 | return Person._instance;
256 | }
257 | }
258 |
259 | const person1 = Person.getInstance();
260 | const person2 = Person.getInstance();
261 |
262 | console.log(person1 === person2);
263 | */
264 |
265 |
266 | /***************************************************
267 | * ***********LECTURE 48: INTERFACE*****************
268 | ***************************************************/
269 | /*interface Roles{
270 | getRole(): string;
271 | }
272 |
273 | interface User extends Roles{
274 | firstname: string;
275 | lastname: string;
276 | readonly company: string;
277 | location?: string;
278 |
279 | greetUser(): void;
280 | getFullName(): string;
281 | }
282 |
283 | class Admin implements User{
284 | age: number = 30;
285 | company: string = 'Google';
286 | constructor(public firstname: string, public lastname: string){
287 |
288 | }
289 |
290 | greetUser(){
291 | console.log("Hello Admin: " + this.getFullName())
292 | }
293 |
294 | getFullName(): string {
295 | return this.firstname + ' ' + this.lastname;
296 | }
297 |
298 | getRole(): string {
299 | return 'admin';
300 | }
301 | }
302 |
303 | class Member implements User{
304 | company: string = 'Google';
305 | location?: string | undefined = 'London';
306 | constructor(public firstname: string, public lastname: string, loc?: string){
307 | this.location = loc;
308 | }
309 |
310 | greetUser(){
311 | console.log("Hello Member: " + this.getFullName())
312 | }
313 |
314 | getFullName(): string {
315 | return this.firstname + ' ' + this.lastname;
316 | }
317 |
318 | getRole(): string {
319 | return 'member';
320 | }
321 | }
322 |
323 | function displayGreetMessage(user: User){
324 | user.greetUser();
325 | }
326 |
327 | let admin: User;
328 | admin = new Admin('john', 'smith');
329 | console.log(admin.getRole());
330 |
331 | const member = new Member('merry', 'jane');
332 |
333 | displayGreetMessage(admin);
334 | displayGreetMessage(member);
335 | console.log(member.getRole());
336 | */
337 |
338 |
339 | /***************************************************
340 | * ****LECTURE 51: INTERFACE AS FUNCTION TYPE*******
341 | ***************************************************/
342 | //type SumFn = (num1: number, num2: number) => number;
343 |
344 | interface SumFn{
345 | (num1: number, num2: number): number
346 | }
347 |
348 | let add: SumFn;
349 |
350 | add = (n1: number, n2: number) => {
351 | return n1 + n2;
352 | }
--------------------------------------------------------------------------------
/04-typescript-classes-and-functions/final/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0px;
3 | padding: 0px;
4 | box-sizing: border-box;
5 | }
6 | body{
7 | background-color: #28282B;
8 | color: white;
9 | font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', Verdana, sans-serif;
10 | }
11 | .app-header{
12 | box-shadow: rgb(196, 190, 190) 0px 2px 8px 0px;
13 | padding: 15px 30px;
14 | }
15 | .app-topic{
16 | padding: 30px 30px;
17 | margin: 50px 50px;
18 | box-shadow: rgba(64, 211, 105, 0.35) 0px 5px 15px;
19 | background-color: #2ECC71;
20 | text-align: center;
21 | }
--------------------------------------------------------------------------------
/04-typescript-classes-and-functions/final/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Visit https://aka.ms/tsconfig to read more about this file */
4 |
5 | /* Projects */
6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12 |
13 | /* Language and Environment */
14 | "target": "ES5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16 | // "jsx": "preserve", /* Specify what JSX code is generated. */
17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26 |
27 | /* Modules */
28 | "module": "commonjs", /* Specify what module code is generated. */
29 | "rootDir": "./src", /* Specify the root folder within your source files. */
30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42 | // "resolveJsonModule": true, /* Enable importing .json files. */
43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
45 |
46 | /* JavaScript Support */
47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50 |
51 | /* Emit */
52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58 | "outDir": "./dist", /* Specify an output folder for all emitted files. */
59 | // "removeComments": true, /* Disable emitting comments. */
60 | // "noEmit": true, /* Disable emitting files from a compilation. */
61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68 | // "newLine": "crlf", /* Set the newline character for emitting files. */
69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75 |
76 | /* Interop Constraints */
77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83 |
84 | /* Type Checking */
85 | "strict": true, /* Enable all strict type-checking options. */
86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104 |
105 | /* Completeness */
106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */
108 | },
109 | "include": ["./src"]
110 | }
111 |
--------------------------------------------------------------------------------
/04-typescript-classes-and-functions/start/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Document
8 |
9 |
10 |
11 |
A Complete TypeScript Course
12 |
13 |
14 |
TypeScript Classes & Interface
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/04-typescript-classes-and-functions/start/src/app.ts:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/manojjha86/typescript-complete-course/09193b1ed6d6243509b1b2de2061f7380ea948d9/04-typescript-classes-and-functions/start/src/app.ts
--------------------------------------------------------------------------------
/04-typescript-classes-and-functions/start/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0px;
3 | padding: 0px;
4 | box-sizing: border-box;
5 | }
6 | body{
7 | background-color: #28282B;
8 | color: white;
9 | font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', Verdana, sans-serif;
10 | }
11 | .app-header{
12 | box-shadow: rgb(196, 190, 190) 0px 2px 8px 0px;
13 | padding: 15px 30px;
14 | }
15 | .app-topic{
16 | padding: 30px 30px;
17 | margin: 50px 50px;
18 | box-shadow: rgba(64, 211, 105, 0.35) 0px 5px 15px;
19 | background-color: #2ECC71;
20 | text-align: center;
21 | }
--------------------------------------------------------------------------------
/04-typescript-classes-and-functions/start/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Visit https://aka.ms/tsconfig to read more about this file */
4 |
5 | /* Projects */
6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12 |
13 | /* Language and Environment */
14 | "target": "ES5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16 | // "jsx": "preserve", /* Specify what JSX code is generated. */
17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26 |
27 | /* Modules */
28 | "module": "commonjs", /* Specify what module code is generated. */
29 | "rootDir": "./src", /* Specify the root folder within your source files. */
30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42 | // "resolveJsonModule": true, /* Enable importing .json files. */
43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
45 |
46 | /* JavaScript Support */
47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50 |
51 | /* Emit */
52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58 | "outDir": "./dist", /* Specify an output folder for all emitted files. */
59 | // "removeComments": true, /* Disable emitting comments. */
60 | // "noEmit": true, /* Disable emitting files from a compilation. */
61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68 | // "newLine": "crlf", /* Set the newline character for emitting files. */
69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75 |
76 | /* Interop Constraints */
77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83 |
84 | /* Type Checking */
85 | "strict": true, /* Enable all strict type-checking options. */
86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104 |
105 | /* Completeness */
106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */
108 | },
109 | "include": ["./src"]
110 | }
111 |
--------------------------------------------------------------------------------
/05-typescript-advanced-types/final/dist/app.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | /***********************************************
3 | * *****INTERSECTION TYPE IN TYPESCRIPT*********
4 | ***********************************************/
5 | /*type stringOrNumber = string | number;
6 | type boolOrNumber = boolean | number;
7 |
8 | type myNumberType = stringOrNumber & boolOrNumber;
9 |
10 | let x: myNumberType = 20;*/
11 | /*interface user {
12 | name: string,
13 | age: number
14 | }
15 |
16 | interface admin {
17 | name: string,
18 | role: string
19 | }
20 |
21 | type adminUser = user & admin;
22 |
23 | var john: adminUser = {
24 | name: 'john',
25 | age: 28,
26 | role: 'admin'
27 | }*/
28 | /*function processOrder(order: Order & { status: string } ){
29 | console.log(order.id, order.items, order.status)
30 | }
31 |
32 | interface Order{
33 | id: number,
34 | items: string[]
35 | }
36 |
37 | processOrder({id: 123, items: ['item1', 'item2'], status: 'shiped'})
38 | */
39 | /***********************************************
40 | * *****TYPE GUARDS IN TYPESCRIPT***************
41 | ***********************************************/
42 | //type StringOrNumber = string | number;
43 | /*function addition(a: StringOrNumber, b: StringOrNumber){
44 | if(typeof a === 'string' || typeof b === 'string'){
45 | return a.toString() + b.toString();
46 | }
47 | return a + b;
48 | }
49 |
50 | addition('hello', 'world');
51 | addition(20, 30);
52 | addition('hello', 30);*/
53 | /*class Animal{
54 | makeSound(){
55 | console.log('Generic animal sound');
56 | }
57 | }
58 |
59 | class Dog extends Animal{
60 | bark(){
61 | console.log('woof woof')
62 | }
63 | }*/
64 | //Classes
65 | /*function makeCreatureSound(creature: Animal){
66 | if(creature instanceof Dog){
67 | creature.bark()
68 | }else{
69 | creature.makeSound();
70 | }
71 | }
72 |
73 | let animal = new Animal();
74 | let dog = new Dog();
75 |
76 | makeCreatureSound(animal);
77 | makeCreatureSound(dog);
78 | */
79 | /*interface User {
80 | name: string,
81 | email?: string;
82 | }
83 |
84 | function greetUser(user: User){
85 | if('email' in user){
86 | console.log(`Hello ${user.name}. Your email is: ${user.email}`);
87 | }else{
88 | console.log(`Hello ${user.name}.`);
89 | }
90 |
91 | }
92 |
93 | greetUser({name: 'john'});
94 | greetUser({name: 'mark', email: 'mark@gmail.com'});
95 | */
96 | /***********************************************
97 | * *****DISCRIMINATED UNION*********************
98 | ***********************************************/
99 | /*interface circle{
100 | kind: 'circle';
101 | radius: number;
102 | }
103 |
104 | interface square{
105 | kind: 'square';
106 | length: number;
107 | }
108 |
109 | type Shape = circle | square;
110 |
111 | function calcArea(shape: Shape){
112 | switch(shape.kind) {
113 | case 'circle':
114 | return 3.14 * shape.radius * shape.radius;
115 | case 'square':
116 | return shape.length * shape.length;
117 | }
118 | }
119 |
120 | console.log(calcArea({kind: 'square', length: 12}))
121 | console.log(calcArea({kind: 'circle',radius: 12}))
122 | */
123 | /***********************************************
124 | * *****TYPE CASTING IN TYPESCRIPT**************
125 | ***********************************************/
126 | // let fname = document.querySelector('#fname')!;
127 | /*let fname = document.querySelector('#fname');
128 | if(fname){
129 | (fname as HTMLInputElement).value = 'John'
130 | }*/
131 | /***********************************************
132 | * *****INDEX PROPERTIES************************
133 | ***********************************************/
134 | /*interface Product{
135 | id: number;
136 | name: string;
137 | [prop: string]: string | number
138 | }
139 |
140 | const product1: Product = {
141 | id: 1,
142 | name: "T-Shirt",
143 | color: 'Red',
144 | price: 123
145 | }
146 |
147 | const product2: Product = {
148 | id: 2,
149 | name: "Mug",
150 | material: 'Ceramic',
151 | capacity: 300
152 | }
153 |
154 | interface Settings{
155 | [props: string]: boolean | string | number
156 | }
157 |
158 | const mySettings: Settings = {
159 | darkMode: true,
160 | fontSize: 16,
161 | customTheme: 'pink'
162 | }
163 |
164 | interface User{
165 | name: string;
166 | [prop: string]: any
167 | }
168 |
169 | const users: User[] = [
170 | {name: 'John', age: 30, gender: 'male'},
171 | {name: 'Mark', interests: ['music', 'sports'], location: 'london'}
172 | ]*/
173 | /***********************************************
174 | * *****FUNCTION OVERLOADING********************
175 | ***********************************************/
176 | /*type StringOrNumber = string | number;
177 |
178 | function addition(a: number, b: number): number;
179 | function addition(a: string, b: string): string;
180 | function addition(a: number, b: string): string;
181 | function addition(a: string, b: number): string;
182 | function addition(a: StringOrNumber, b: StringOrNumber){
183 | if(typeof a === 'string' || typeof b === 'string'){
184 | return a.toString() + b.toString();
185 | }
186 | return a + b;
187 | }
188 |
189 | addition('Hello', 'World').split(',');
190 | addition(10, 20);
191 | */
192 | /***********************************************
193 | * *****WHAT ARE GENERICS***********************
194 | ***********************************************/
195 | /*function swap(arr: T[], index1: number, index2: number): T[]{
196 | //swapping logic
197 | return [];
198 | }
199 | swap([1, 2, 3], 0, 2);
200 | swap(['Hello', 'Hi', 'How are you'], 1, 2);
201 |
202 | const p: Promise = new Promise((resolve, reject) => {
203 | setTimeout(() => {
204 | resolve(100);
205 | }, 1000)
206 | });*/
207 | /***********************************************
208 | * *****CREATING A GENERIC FUNCTION*************
209 | ***********************************************/
210 | /*function swap(arr: T[], index1: number, index2: number): T[]{
211 | //swapping logic
212 | if(
213 | index1 < 0 || index1 >= arr.length
214 | || index2 < 0 || index2 >= arr.length
215 | )
216 | {
217 | throw new Error('Invalid index');
218 | }
219 | [arr[index1], arr[index2]] = [arr[index2], arr[index1]];
220 | return arr;
221 | }
222 | console.log(swap([1, 2, 3], 0, 2));
223 | console.log(swap(['Hello', 'Hi', 'How are you'], 1, 2));
224 |
225 |
226 | function expand(obj1: T , obj2: U){
227 | return Object.assign(obj1, obj2);
228 | }
229 |
230 | let combined = expand({name: 'john', age: 28}, {name: 'john', gender: 'male'});
231 | console.log(combined);
232 | */
233 | /***********************************************
234 | * *****THE KEYOF CONSTRAINT********************
235 | ***********************************************/
236 | /*function getPropValue(obj: T, key: U){
237 | return obj[key];
238 | }
239 |
240 | getPropValue({name: 'john', age: 28}, 'age');
241 | */
242 | /***********************************************
243 | * *****CREATING A GENERIC CLASS****************
244 | ***********************************************/
245 | /*type Book = {
246 | name: string;
247 | pages: number;
248 | price: number
249 | }
250 |
251 | type Cloth = {
252 | name: string;
253 | size: string;
254 | price: number
255 | }
256 |
257 | class ShoppingKart{
258 | private items: T[] = [];
259 |
260 | addItem(item: T){
261 | this.items.push(item);
262 | }
263 | getItems(){
264 | return this.items
265 | }
266 | }
267 |
268 | const bookCart = new ShoppingKart();
269 | bookCart.addItem({name: 'A Book', pages: 225, price: 20});
270 | bookCart.addItem({name: 'Another Book', pages: 250, price: 25});
271 | console.log(bookCart.getItems());
272 |
273 | const clothCart = new ShoppingKart();
274 | clothCart.addItem({name: 'T-Shirt', size: 'M', price: 225});
275 | console.log(clothCart.getItems());
276 |
277 | const strkart = new ShoppingKart();
278 | strkart.addItem('Hello');
279 | strkart.addItem('World');
280 | console.log(strkart.getItems())
281 | */
282 | /***********************************************
283 | * *****GENERIC TYPE VS UNION TYPE**************
284 | ***********************************************/
285 | /*class ShoppingKart{
286 | private items: T[]= [];
287 |
288 | addItem(item: T){
289 | this.items.push(item);
290 | }
291 | getItems(){
292 | return this.items
293 | }
294 | }
295 |
296 |
297 | const strkart = new ShoppingKart();
298 | strkart.addItem('Hello');
299 | strkart.addItem('World');
300 | console.log(strkart.getItems())
301 |
302 | const numkart = new ShoppingKart();
303 | numkart.addItem(200);
304 | numkart.addItem(300);
305 | console.log(numkart.getItems())
306 | */
307 | /***********************************************
308 | * *****PARTIAL & READ ONLY GENERICS************
309 | ***********************************************/
310 | /*interface UserSettings{
311 | username: string;
312 | email: string;
313 | darkMode: boolean;
314 | language: string;
315 | }
316 |
317 | function updateUserSettings(partialsettings: Partial){
318 | console.log('Updating:', partialsettings)
319 | }
320 |
321 | const user: Readonly = {
322 | username: 'johnsmith',
323 | email: 'johnsmith@gmail.com',
324 | darkMode: false,
325 | language: 'en'
326 | }
327 |
328 | user.username = 'something';
329 |
330 | const newSettings = {
331 | darkMode: true,
332 | language: 'fr'
333 | }
334 | updateUserSettings(newSettings)
335 |
336 |
337 |
338 | let arr: Readonly = ['john', 'mark'];
339 | arr.push('merry');
340 | console.log(arr);
341 | */
342 |
--------------------------------------------------------------------------------
/05-typescript-advanced-types/final/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Document
8 |
9 |
10 |
11 |
A Complete TypeScript Course
12 |
13 |
14 |
TypeScript Advanced Types
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/05-typescript-advanced-types/final/src/app.ts:
--------------------------------------------------------------------------------
1 | /***********************************************
2 | * *****INTERSECTION TYPE IN TYPESCRIPT*********
3 | ***********************************************/
4 | /*type stringOrNumber = string | number;
5 | type boolOrNumber = boolean | number;
6 |
7 | type myNumberType = stringOrNumber & boolOrNumber;
8 |
9 | let x: myNumberType = 20;*/
10 |
11 | /*interface user {
12 | name: string,
13 | age: number
14 | }
15 |
16 | interface admin {
17 | name: string,
18 | role: string
19 | }
20 |
21 | type adminUser = user & admin;
22 |
23 | var john: adminUser = {
24 | name: 'john',
25 | age: 28,
26 | role: 'admin'
27 | }*/
28 |
29 | /*function processOrder(order: Order & { status: string } ){
30 | console.log(order.id, order.items, order.status)
31 | }
32 |
33 | interface Order{
34 | id: number,
35 | items: string[]
36 | }
37 |
38 | processOrder({id: 123, items: ['item1', 'item2'], status: 'shiped'})
39 | */
40 |
41 |
42 |
43 | /***********************************************
44 | * *****TYPE GUARDS IN TYPESCRIPT***************
45 | ***********************************************/
46 | //type StringOrNumber = string | number;
47 |
48 | /*function addition(a: StringOrNumber, b: StringOrNumber){
49 | if(typeof a === 'string' || typeof b === 'string'){
50 | return a.toString() + b.toString();
51 | }
52 | return a + b;
53 | }
54 |
55 | addition('hello', 'world');
56 | addition(20, 30);
57 | addition('hello', 30);*/
58 |
59 | /*class Animal{
60 | makeSound(){
61 | console.log('Generic animal sound');
62 | }
63 | }
64 |
65 | class Dog extends Animal{
66 | bark(){
67 | console.log('woof woof')
68 | }
69 | }*/
70 |
71 | //Classes
72 | /*function makeCreatureSound(creature: Animal){
73 | if(creature instanceof Dog){
74 | creature.bark()
75 | }else{
76 | creature.makeSound();
77 | }
78 | }
79 |
80 | let animal = new Animal();
81 | let dog = new Dog();
82 |
83 | makeCreatureSound(animal);
84 | makeCreatureSound(dog);
85 | */
86 |
87 | /*interface User {
88 | name: string,
89 | email?: string;
90 | }
91 |
92 | function greetUser(user: User){
93 | if('email' in user){
94 | console.log(`Hello ${user.name}. Your email is: ${user.email}`);
95 | }else{
96 | console.log(`Hello ${user.name}.`);
97 | }
98 |
99 | }
100 |
101 | greetUser({name: 'john'});
102 | greetUser({name: 'mark', email: 'mark@gmail.com'});
103 | */
104 |
105 |
106 |
107 |
108 | /***********************************************
109 | * *****DISCRIMINATED UNION*********************
110 | ***********************************************/
111 | /*interface circle{
112 | kind: 'circle';
113 | radius: number;
114 | }
115 |
116 | interface square{
117 | kind: 'square';
118 | length: number;
119 | }
120 |
121 | type Shape = circle | square;
122 |
123 | function calcArea(shape: Shape){
124 | switch(shape.kind) {
125 | case 'circle':
126 | return 3.14 * shape.radius * shape.radius;
127 | case 'square':
128 | return shape.length * shape.length;
129 | }
130 | }
131 |
132 | console.log(calcArea({kind: 'square', length: 12}))
133 | console.log(calcArea({kind: 'circle',radius: 12}))
134 | */
135 |
136 |
137 |
138 | /***********************************************
139 | * *****TYPE CASTING IN TYPESCRIPT**************
140 | ***********************************************/
141 | // let fname = document.querySelector('#fname')!;
142 | /*let fname = document.querySelector('#fname');
143 | if(fname){
144 | (fname as HTMLInputElement).value = 'John'
145 | }*/
146 |
147 |
148 | /***********************************************
149 | * *****INDEX PROPERTIES************************
150 | ***********************************************/
151 | /*interface Product{
152 | id: number;
153 | name: string;
154 | [prop: string]: string | number
155 | }
156 |
157 | const product1: Product = {
158 | id: 1,
159 | name: "T-Shirt",
160 | color: 'Red',
161 | price: 123
162 | }
163 |
164 | const product2: Product = {
165 | id: 2,
166 | name: "Mug",
167 | material: 'Ceramic',
168 | capacity: 300
169 | }
170 |
171 | interface Settings{
172 | [props: string]: boolean | string | number
173 | }
174 |
175 | const mySettings: Settings = {
176 | darkMode: true,
177 | fontSize: 16,
178 | customTheme: 'pink'
179 | }
180 |
181 | interface User{
182 | name: string;
183 | [prop: string]: any
184 | }
185 |
186 | const users: User[] = [
187 | {name: 'John', age: 30, gender: 'male'},
188 | {name: 'Mark', interests: ['music', 'sports'], location: 'london'}
189 | ]*/
190 |
191 |
192 | /***********************************************
193 | * *****FUNCTION OVERLOADING********************
194 | ***********************************************/
195 | /*type StringOrNumber = string | number;
196 |
197 | function addition(a: number, b: number): number;
198 | function addition(a: string, b: string): string;
199 | function addition(a: number, b: string): string;
200 | function addition(a: string, b: number): string;
201 | function addition(a: StringOrNumber, b: StringOrNumber){
202 | if(typeof a === 'string' || typeof b === 'string'){
203 | return a.toString() + b.toString();
204 | }
205 | return a + b;
206 | }
207 |
208 | addition('Hello', 'World').split(',');
209 | addition(10, 20);
210 | */
211 |
212 |
213 |
214 | /***********************************************
215 | * *****WHAT ARE GENERICS***********************
216 | ***********************************************/
217 | /*function swap(arr: T[], index1: number, index2: number): T[]{
218 | //swapping logic
219 | return [];
220 | }
221 | swap([1, 2, 3], 0, 2);
222 | swap(['Hello', 'Hi', 'How are you'], 1, 2);
223 |
224 | const p: Promise = new Promise((resolve, reject) => {
225 | setTimeout(() => {
226 | resolve(100);
227 | }, 1000)
228 | });*/
229 |
230 |
231 |
232 | /***********************************************
233 | * *****CREATING A GENERIC FUNCTION*************
234 | ***********************************************/
235 | /*function swap(arr: T[], index1: number, index2: number): T[]{
236 | //swapping logic
237 | if(
238 | index1 < 0 || index1 >= arr.length
239 | || index2 < 0 || index2 >= arr.length
240 | )
241 | {
242 | throw new Error('Invalid index');
243 | }
244 | [arr[index1], arr[index2]] = [arr[index2], arr[index1]];
245 | return arr;
246 | }
247 | console.log(swap([1, 2, 3], 0, 2));
248 | console.log(swap(['Hello', 'Hi', 'How are you'], 1, 2));
249 |
250 |
251 | function expand(obj1: T , obj2: U){
252 | return Object.assign(obj1, obj2);
253 | }
254 |
255 | let combined = expand({name: 'john', age: 28}, {name: 'john', gender: 'male'});
256 | console.log(combined);
257 | */
258 |
259 |
260 |
261 | /***********************************************
262 | * *****THE KEYOF CONSTRAINT********************
263 | ***********************************************/
264 | /*function getPropValue(obj: T, key: U){
265 | return obj[key];
266 | }
267 |
268 | getPropValue({name: 'john', age: 28}, 'age');
269 | */
270 |
271 |
272 |
273 | /***********************************************
274 | * *****CREATING A GENERIC CLASS****************
275 | ***********************************************/
276 | /*type Book = {
277 | name: string;
278 | pages: number;
279 | price: number
280 | }
281 |
282 | type Cloth = {
283 | name: string;
284 | size: string;
285 | price: number
286 | }
287 |
288 | class ShoppingKart{
289 | private items: T[] = [];
290 |
291 | addItem(item: T){
292 | this.items.push(item);
293 | }
294 | getItems(){
295 | return this.items
296 | }
297 | }
298 |
299 | const bookCart = new ShoppingKart();
300 | bookCart.addItem({name: 'A Book', pages: 225, price: 20});
301 | bookCart.addItem({name: 'Another Book', pages: 250, price: 25});
302 | console.log(bookCart.getItems());
303 |
304 | const clothCart = new ShoppingKart();
305 | clothCart.addItem({name: 'T-Shirt', size: 'M', price: 225});
306 | console.log(clothCart.getItems());
307 |
308 | const strkart = new ShoppingKart();
309 | strkart.addItem('Hello');
310 | strkart.addItem('World');
311 | console.log(strkart.getItems())
312 | */
313 |
314 |
315 |
316 | /***********************************************
317 | * *****GENERIC TYPE VS UNION TYPE**************
318 | ***********************************************/
319 | /*class ShoppingKart{
320 | private items: T[]= [];
321 |
322 | addItem(item: T){
323 | this.items.push(item);
324 | }
325 | getItems(){
326 | return this.items
327 | }
328 | }
329 |
330 |
331 | const strkart = new ShoppingKart();
332 | strkart.addItem('Hello');
333 | strkart.addItem('World');
334 | console.log(strkart.getItems())
335 |
336 | const numkart = new ShoppingKart();
337 | numkart.addItem(200);
338 | numkart.addItem(300);
339 | console.log(numkart.getItems())
340 | */
341 |
342 |
343 |
344 |
345 | /***********************************************
346 | * *****PARTIAL & READ ONLY GENERICS************
347 | ***********************************************/
348 | /*interface UserSettings{
349 | username: string;
350 | email: string;
351 | darkMode: boolean;
352 | language: string;
353 | }
354 |
355 | function updateUserSettings(partialsettings: Partial){
356 | console.log('Updating:', partialsettings)
357 | }
358 |
359 | const user: Readonly = {
360 | username: 'johnsmith',
361 | email: 'johnsmith@gmail.com',
362 | darkMode: false,
363 | language: 'en'
364 | }
365 |
366 | user.username = 'something';
367 |
368 | const newSettings = {
369 | darkMode: true,
370 | language: 'fr'
371 | }
372 | updateUserSettings(newSettings)
373 |
374 |
375 |
376 | let arr: Readonly = ['john', 'mark'];
377 | arr.push('merry');
378 | console.log(arr);
379 | */
--------------------------------------------------------------------------------
/05-typescript-advanced-types/final/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0px;
3 | padding: 0px;
4 | box-sizing: border-box;
5 | }
6 | body{
7 | background-color: #28282B;
8 | color: white;
9 | font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', Verdana, sans-serif;
10 | }
11 | .app-header{
12 | box-shadow: rgb(196, 190, 190) 0px 2px 8px 0px;
13 | padding: 15px 30px;
14 | }
15 | .app-topic{
16 | padding: 30px 30px;
17 | margin: 50px 50px;
18 | box-shadow: rgba(64, 211, 105, 0.35) 0px 5px 15px;
19 | background-color: #2ECC71;
20 | text-align: center;
21 | }
--------------------------------------------------------------------------------
/05-typescript-advanced-types/final/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Visit https://aka.ms/tsconfig to read more about this file */
4 |
5 | /* Projects */
6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12 |
13 | /* Language and Environment */
14 | "target": "ES2015", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16 | // "jsx": "preserve", /* Specify what JSX code is generated. */
17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26 |
27 | /* Modules */
28 | "module": "commonjs", /* Specify what module code is generated. */
29 | "rootDir": "./src", /* Specify the root folder within your source files. */
30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42 | // "resolveJsonModule": true, /* Enable importing .json files. */
43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
45 |
46 | /* JavaScript Support */
47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50 |
51 | /* Emit */
52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58 | "outDir": "./dist", /* Specify an output folder for all emitted files. */
59 | // "removeComments": true, /* Disable emitting comments. */
60 | // "noEmit": true, /* Disable emitting files from a compilation. */
61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68 | // "newLine": "crlf", /* Set the newline character for emitting files. */
69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75 |
76 | /* Interop Constraints */
77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83 |
84 | /* Type Checking */
85 | "strict": true, /* Enable all strict type-checking options. */
86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104 |
105 | /* Completeness */
106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */
108 | },
109 | "include": ["./src"]
110 | }
111 |
--------------------------------------------------------------------------------
/05-typescript-advanced-types/start/dist/app.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/manojjha86/typescript-complete-course/09193b1ed6d6243509b1b2de2061f7380ea948d9/05-typescript-advanced-types/start/dist/app.js
--------------------------------------------------------------------------------
/05-typescript-advanced-types/start/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Document
8 |
9 |
10 |
11 |
A Complete TypeScript Course
12 |
13 |
14 |
TypeScript Advanced Types
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/05-typescript-advanced-types/start/src/app.ts:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/manojjha86/typescript-complete-course/09193b1ed6d6243509b1b2de2061f7380ea948d9/05-typescript-advanced-types/start/src/app.ts
--------------------------------------------------------------------------------
/05-typescript-advanced-types/start/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0px;
3 | padding: 0px;
4 | box-sizing: border-box;
5 | }
6 | body{
7 | background-color: #28282B;
8 | color: white;
9 | font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', Verdana, sans-serif;
10 | }
11 | .app-header{
12 | box-shadow: rgb(196, 190, 190) 0px 2px 8px 0px;
13 | padding: 15px 30px;
14 | }
15 | .app-topic{
16 | padding: 30px 30px;
17 | margin: 50px 50px;
18 | box-shadow: rgba(64, 211, 105, 0.35) 0px 5px 15px;
19 | background-color: #2ECC71;
20 | text-align: center;
21 | }
--------------------------------------------------------------------------------
/05-typescript-advanced-types/start/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Visit https://aka.ms/tsconfig to read more about this file */
4 |
5 | /* Projects */
6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12 |
13 | /* Language and Environment */
14 | "target": "ES2015", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16 | // "jsx": "preserve", /* Specify what JSX code is generated. */
17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26 |
27 | /* Modules */
28 | "module": "commonjs", /* Specify what module code is generated. */
29 | "rootDir": "./src", /* Specify the root folder within your source files. */
30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42 | // "resolveJsonModule": true, /* Enable importing .json files. */
43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
45 |
46 | /* JavaScript Support */
47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50 |
51 | /* Emit */
52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58 | "outDir": "./dist", /* Specify an output folder for all emitted files. */
59 | // "removeComments": true, /* Disable emitting comments. */
60 | // "noEmit": true, /* Disable emitting files from a compilation. */
61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68 | // "newLine": "crlf", /* Set the newline character for emitting files. */
69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75 |
76 | /* Interop Constraints */
77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83 |
84 | /* Type Checking */
85 | "strict": true, /* Enable all strict type-checking options. */
86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104 |
105 | /* Completeness */
106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */
108 | },
109 | "include": ["./src"]
110 | }
111 |
--------------------------------------------------------------------------------
/06-typescript-expense-tracker/final/dist/app.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | //ACCESS DOM ELEMENTS FROM TYPESCRIPT
3 | const expType = document.getElementById('expense-type');
4 | const expDesc = document.getElementById('desc');
5 | const expAmt = document.getElementById('amount');
6 | const addExpBtn = document.querySelector('.add-expense-btn');
7 | const debitDiv = document.querySelector('.expense-debit-item-container');
8 | const creditDiv = document.querySelector('.expense-credit-item-container');
9 | const totalAmtDiv = document.querySelector('.total-expense-amount');
10 | let expenseItems = [];
11 | let totalAmount = 0;
12 | class Expense {
13 | constructor(type, desc, amount) {
14 | this.id = 0;
15 | this.type = 'debit';
16 | this.description = '';
17 | this.amount = 0;
18 | this.type = type;
19 | this.description = desc;
20 | this.amount = amount;
21 | this.id = ++Expense.currentId;
22 | }
23 | }
24 | Expense.currentId = 0;
25 | function DisplayExpenseItems() {
26 | debitDiv.innerHTML = '';
27 | creditDiv.innerHTML = '';
28 | for (let i = 0; i < expenseItems.length; i++) {
29 | let expItem = expenseItems[i];
30 | let containerDiv = expItem.type === 'credit' ? creditDiv : debitDiv;
31 | let cssClass = expItem.type === 'credit' ? 'credit-item' : 'debit-item';
32 | let template = `
33 |
', 'container')
34 | class User{
35 | name: string = 'John';
36 | age: number = 28;
37 |
38 | constructor(){
39 | console.log('User class constructor called...')
40 | }
41 | }
42 |
43 | //const u = new User();
44 | */
45 |
46 |
47 |
48 | /***********************************************
49 | * *****PROPERTY DECORATOR**********************
50 | ***********************************************/
51 | /*function Capitalize(target: any, propertyKey: string): any{
52 | let value: string;
53 |
54 | const getter = function(){
55 | return value.charAt(0).toUpperCase() + value.slice(1); // S + amsung
56 | }
57 |
58 | const setter = function(newValue: string){
59 | value = newValue.toLowerCase()
60 | }
61 |
62 | return {
63 | get: getter,
64 | set: setter
65 | }
66 | }
67 |
68 | function AccessLogger(target: any, name: string, descriptor: PropertyDescriptor){
69 | const getter = descriptor.get;
70 | const setter = descriptor.set;
71 |
72 | descriptor.get = function(){
73 | console.log(`Accessing value for property ${name}...`);
74 | if(getter){
75 | return getter.call(this);
76 | }
77 | return undefined;
78 | }
79 |
80 | descriptor.set = function(value: number){
81 | console.log(`Setting value for property ${name}...`);
82 | if(setter){
83 | setter.call(this, value);
84 | }
85 | }
86 |
87 | return descriptor;
88 | }
89 |
90 | class Product{
91 | @Capitalize
92 | name: string;
93 |
94 | private _price: number;
95 |
96 | @AccessLogger
97 | get price(){
98 | return this._price;
99 | }
100 |
101 | set price(value: number){
102 | if(value > 0){
103 | this._price = value;
104 | }else{
105 | throw new Error("Price should be a value greater than zero");
106 | }
107 | }
108 |
109 | constructor(name: string, price: number){
110 | this.name = name;
111 | this._price = price;
112 | }
113 | }
114 |
115 | const p = new Product('apple', 2400);
116 | p.price = 3000;
117 | console.log(p.price);
118 | */
119 |
120 |
121 |
122 | /***********************************************
123 | * *****WHEN A DECORATOR EXECUTES***************
124 | ***********************************************/
125 | /*function CLS_DECORATOR(target: any){
126 | console.log('CLASS DECORATOR CALLED!');
127 | }
128 |
129 | function PROP_DECORATOR(target: any, propertyKey: string): any{
130 | console.log('PROPERTY DECORATOR CALLED!');
131 | }
132 |
133 | function ACC_DECORATOR(target: any, name: string, descriptor: PropertyDescriptor){
134 | console.log('ACCESSOR DECORATOR CALLED');
135 | }
136 |
137 | function PARAM_DECORATOR(target: any, paramName: string, index: number){
138 | console.log('PARAMETER DECORATOR CALLED');
139 | }
140 |
141 | function METH_DECORATOR(target: any, methodName: string, descriptor: PropertyDescriptor){
142 | console.log('METHOD DECORATOR CALLED!');
143 | }
144 |
145 | @CLS_DECORATOR
146 | class Person{
147 | @PROP_DECORATOR
148 | name: string;
149 |
150 | constructor(n: string){
151 | this.name = n;
152 | }
153 |
154 | @METH_DECORATOR
155 | calculateAge(@PARAM_DECORATOR dob: string){
156 | //calculate date of birth;
157 | }
158 | }
159 | */
160 |
161 |
162 |
163 | /***********************************************
164 | * *****RETURNING A CLASS FROM A DECORATOR *****
165 | ***********************************************/
166 | /*function Logger(target: new (...args: any[]) => {}): any{
167 | class LoggingClass extends target{
168 | static company: string = 'Google';
169 | constructor(...args: any[]){
170 | super(...args);
171 | console.log('Creating a new LoggingClass Instance...')
172 | }
173 | }
174 |
175 | return LoggingClass;
176 | }
177 |
178 | @Logger
179 | class Person{
180 | name: string;
181 |
182 | constructor(n: string){
183 | this.name = n;
184 | }
185 | }
186 |
187 | const p = new Person('john');
188 | console.log(p);
189 | */
190 |
191 |
192 |
193 | /***********************************************
194 | * *****CREATING A VALIDATION DECORATOR*** *****
195 | ***********************************************/
196 | function required(target: any, propName: string){
197 | validateObject[target.constructor.name]= {
198 | ...validateObject[target.constructor.name],
199 | [propName]: ['required']
200 | }
201 | }
202 |
203 | function minlength(length: number){
204 | return function(target: any, propName: string){
205 | validateObject[target.constructor.name]= {
206 | ...validateObject[target.constructor.name],
207 | [propName]: ['minlength']
208 | }
209 | }
210 | }
211 | function positiveNumber(target: any, propName: string){
212 | validateObject[target.constructor.name]= {
213 | ...validateObject[target.constructor.name],
214 | [propName]: ['positiveNumber']
215 | }
216 | }
217 |
218 | interface IValidator{
219 | [prop: string]: {
220 | [propKey: string]: string[]; // ['required', 'minlength']
221 | }
222 | }
223 |
224 | const validateObject: IValidator = {};
225 |
226 | function validate(obj: any): boolean{
227 | let isValid = true;
228 |
229 | const validateClass = validateObject[obj.constructor.name];
230 | if(!validateClass){
231 | return true;
232 | }
233 |
234 | for(let prop in validateClass){
235 | for (let validator of validateClass[prop]){
236 | switch(validator){
237 | case 'required':
238 | isValid = isValid && !!obj[prop];
239 | break;
240 | case 'minlength':
241 | isValid = isValid && obj[prop].length < 3;
242 | break;
243 | case 'positiveNumber':
244 | isValid = isValid && obj[prop].length < 0;
245 | break;
246 | }
247 | }
248 | }
249 |
250 | return isValid;
251 |
252 | }
253 |
254 | class User{
255 | @required
256 | @minlength(3)
257 | username: string;
258 |
259 | @positiveNumber
260 | age: number;
261 |
262 | constructor(uname: string, age: number){
263 | this.username = uname;
264 | this.age = age;
265 | }
266 | }
267 |
268 | const u1 = new User('john', 28);
269 | const u2 = new User('', 30);
270 |
271 | if(!validate(u2)){
272 | alert("Invalid Input.");
273 | }else{
274 | console.log('user created successfully');
275 | }
--------------------------------------------------------------------------------
/07-typescript-decorators/final/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0px;
3 | padding: 0px;
4 | box-sizing: border-box;
5 | }
6 | body{
7 | background-color: #28282B;
8 | color: white;
9 | font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', Verdana, sans-serif;
10 | }
11 | .app-header{
12 | box-shadow: rgb(196, 190, 190) 0px 2px 8px 0px;
13 | padding: 15px 30px;
14 | }
15 | .app-topic{
16 | padding: 30px 30px;
17 | margin: 50px 50px;
18 | box-shadow: rgba(64, 211, 105, 0.35) 0px 5px 15px;
19 | background-color: #2ECC71;
20 | text-align: center;
21 | }
--------------------------------------------------------------------------------
/07-typescript-decorators/final/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Visit https://aka.ms/tsconfig to read more about this file */
4 |
5 | /* Projects */
6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12 |
13 | /* Language and Environment */
14 | "target": "ES2015", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16 | // "jsx": "preserve", /* Specify what JSX code is generated. */
17 | "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26 |
27 | /* Modules */
28 | "module": "commonjs", /* Specify what module code is generated. */
29 | "rootDir": "./src", /* Specify the root folder within your source files. */
30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42 | // "resolveJsonModule": true, /* Enable importing .json files. */
43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
45 |
46 | /* JavaScript Support */
47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50 |
51 | /* Emit */
52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58 | "outDir": "./dist", /* Specify an output folder for all emitted files. */
59 | // "removeComments": true, /* Disable emitting comments. */
60 | // "noEmit": true, /* Disable emitting files from a compilation. */
61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68 | // "newLine": "crlf", /* Set the newline character for emitting files. */
69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75 |
76 | /* Interop Constraints */
77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83 |
84 | /* Type Checking */
85 | "strict": true, /* Enable all strict type-checking options. */
86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104 |
105 | /* Completeness */
106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */
108 | },
109 | "include": ["./src"]
110 | }
111 |
--------------------------------------------------------------------------------
/07-typescript-decorators/start/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Document
8 |
9 |
10 |
11 |
A Complete TypeScript Course
12 |
13 |
14 |
Decorators in TypeScript
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/07-typescript-decorators/start/src/app.ts:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/manojjha86/typescript-complete-course/09193b1ed6d6243509b1b2de2061f7380ea948d9/07-typescript-decorators/start/src/app.ts
--------------------------------------------------------------------------------
/07-typescript-decorators/start/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0px;
3 | padding: 0px;
4 | box-sizing: border-box;
5 | }
6 | body{
7 | background-color: #28282B;
8 | color: white;
9 | font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', Verdana, sans-serif;
10 | }
11 | .app-header{
12 | box-shadow: rgb(196, 190, 190) 0px 2px 8px 0px;
13 | padding: 15px 30px;
14 | }
15 | .app-topic{
16 | padding: 30px 30px;
17 | margin: 50px 50px;
18 | box-shadow: rgba(64, 211, 105, 0.35) 0px 5px 15px;
19 | background-color: #2ECC71;
20 | text-align: center;
21 | }
--------------------------------------------------------------------------------
/07-typescript-decorators/start/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Visit https://aka.ms/tsconfig to read more about this file */
4 |
5 | /* Projects */
6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12 |
13 | /* Language and Environment */
14 | "target": "ES2015", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16 | // "jsx": "preserve", /* Specify what JSX code is generated. */
17 | "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26 |
27 | /* Modules */
28 | "module": "commonjs", /* Specify what module code is generated. */
29 | "rootDir": "./src", /* Specify the root folder within your source files. */
30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42 | // "resolveJsonModule": true, /* Enable importing .json files. */
43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
45 |
46 | /* JavaScript Support */
47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50 |
51 | /* Emit */
52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58 | "outDir": "./dist", /* Specify an output folder for all emitted files. */
59 | // "removeComments": true, /* Disable emitting comments. */
60 | // "noEmit": true, /* Disable emitting files from a compilation. */
61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68 | // "newLine": "crlf", /* Set the newline character for emitting files. */
69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75 |
76 | /* Interop Constraints */
77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83 |
84 | /* Type Checking */
85 | "strict": true, /* Enable all strict type-checking options. */
86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104 |
105 | /* Completeness */
106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */
108 | },
109 | "include": ["./src"]
110 | }
111 |
--------------------------------------------------------------------------------
/08-typesctipt-namespace/final/dist/app.js:
--------------------------------------------------------------------------------
1 | //Understanding NameSpace in TypeScript
2 | import * as actions from './userUtils/user-actions.js';
3 | const u1 = actions.createUser('john', 28, 'male');
4 | const u2 = actions.createUser('mery', 30, 'female');
5 | console.log(u1, u2);
6 | console.log(actions.getUsers());
7 |
--------------------------------------------------------------------------------
/08-typesctipt-namespace/final/dist/models/user.js:
--------------------------------------------------------------------------------
1 | export default class User {
2 | constructor(name, age, gender) {
3 | this.name = name;
4 | this.age = age;
5 | this.gender = gender;
6 | }
7 | }
8 | export const PI = 3.14;
9 | console.log('User.js file executing');
10 |
--------------------------------------------------------------------------------
/08-typesctipt-namespace/final/dist/userUtils/user-actions.js:
--------------------------------------------------------------------------------
1 | import User from './../models/user.js';
2 | let userList = [];
3 | export function createUser(name, age, gender) {
4 | const u = new User(name, age, gender);
5 | userList.push(u);
6 | return u;
7 | }
8 | export function getUsers() {
9 | return userList;
10 | }
11 |
--------------------------------------------------------------------------------
/08-typesctipt-namespace/final/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Document
8 |
9 |
10 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/08-typesctipt-namespace/start/src/app.ts:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/manojjha86/typescript-complete-course/09193b1ed6d6243509b1b2de2061f7380ea948d9/08-typesctipt-namespace/start/src/app.ts
--------------------------------------------------------------------------------
/08-typesctipt-namespace/start/style.css:
--------------------------------------------------------------------------------
1 | *{
2 | margin: 0px;
3 | padding: 0px;
4 | box-sizing: border-box;
5 | }
6 | body{
7 | background-color: #28282B;
8 | color: white;
9 | font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', Verdana, sans-serif;
10 | }
11 | .app-header{
12 | box-shadow: rgb(196, 190, 190) 0px 2px 8px 0px;
13 | padding: 15px 30px;
14 | }
15 | .app-topic{
16 | padding: 30px 30px;
17 | margin: 50px 50px;
18 | box-shadow: rgba(64, 211, 105, 0.35) 0px 5px 15px;
19 | background-color: #2ECC71;
20 | text-align: center;
21 | }
--------------------------------------------------------------------------------
/08-typesctipt-namespace/start/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Visit https://aka.ms/tsconfig to read more about this file */
4 |
5 | /* Projects */
6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12 |
13 | /* Language and Environment */
14 | "target": "ES2015", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16 | // "jsx": "preserve", /* Specify what JSX code is generated. */
17 | "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26 |
27 | /* Modules */
28 | "module": "commonjs", /* Specify what module code is generated. */
29 | "rootDir": "./src", /* Specify the root folder within your source files. */
30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42 | // "resolveJsonModule": true, /* Enable importing .json files. */
43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
45 |
46 | /* JavaScript Support */
47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50 |
51 | /* Emit */
52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58 | "outDir": "./dist", /* Specify an output folder for all emitted files. */
59 | // "removeComments": true, /* Disable emitting comments. */
60 | // "noEmit": true, /* Disable emitting files from a compilation. */
61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68 | // "newLine": "crlf", /* Set the newline character for emitting files. */
69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75 |
76 | /* Interop Constraints */
77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83 |
84 | /* Type Checking */
85 | "strict": true, /* Enable all strict type-checking options. */
86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104 |
105 | /* Completeness */
106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */
108 | },
109 | "include": ["./src"]
110 | }
111 |
--------------------------------------------------------------------------------