typescript demo step by step

This commit is contained in:
Primakov Alexandr Alexandrovich 2024-10-09 00:16:12 +03:00
commit 14bd95b5ae
31 changed files with 2012 additions and 0 deletions

15
01_simple/Readme.md Normal file
View File

@ -0,0 +1,15 @@
Для того что бы увидеть как typescript подсветит ошибку необходимо выполнить шаги:
1. Установка
```shell
npm install -g typescript
```
2. Переименовываем файл
> index.js -> index.ts
3. Наблюдаем результат
![screenshot](../assets/01.png)

6
01_simple/index.ts Normal file
View File

@ -0,0 +1,6 @@
const square = { width: 10, height: 10 };
const check = () => console.log(square.width * square.heigth);

View File

@ -0,0 +1,6 @@
import { add } from './utils';
const a = 1;
const b = 22;
console.info(add(a, b));

View File

@ -0,0 +1 @@
export const add = (a: number, b: number) => a + b;

View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "UMD", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"outDir": "dist"
},
"files": [
"src/index.ts"
],
"exclude": [
"node_modules",
"**/*.ts"
]
}

1
03_more_options/dist/index.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export {};

6
03_more_options/dist/index.js vendored Normal file
View File

@ -0,0 +1,6 @@
import { add } from './utils';
const a = 1;
const b = 2;
const c = 3;
console.info(add(a, b));
//# sourceMappingURL=index.js.map

1
03_more_options/dist/index.js.map vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAE9B,MAAM,CAAC,GAAW,CAAC,CAAC;AACpB,MAAM,CAAC,GAAW,CAAC,CAAC;AACpB,MAAM,CAAC,GAAG,CAAC,CAAC;AAEZ,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAA"}

16
03_more_options/dist/utils.d.ts vendored Normal file
View File

@ -0,0 +1,16 @@
export declare const add: (a: number, b: number) => string | number;
interface Cat {
name?: {
fistName: string;
lastName: string;
age: number;
};
}
/**
* getCatName в консоль.
*
* @param {Cat} cat Сообщение.
* @param {number} notCat Тип сообщения.
*/
export declare const getCatName: (cat: Cat, notCat: number) => string | undefined;
export {};

16
03_more_options/dist/utils.js vendored Normal file
View File

@ -0,0 +1,16 @@
export const add = (a, b) => {
if (a > 0) {
return a + b;
}
return '' + a + b;
};
/**
* getCatName в консоль.
*
* @param {Cat} cat Сообщение.
* @param {number} notCat Тип сообщения.
*/
export const getCatName = (cat, notCat) => {
return cat.name && cat.name.fistName;
};
//# sourceMappingURL=utils.js.map

1
03_more_options/dist/utils.js.map vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,EAAE;IACxC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QACR,OAAO,CAAC,GAAG,CAAC,CAAA;IAChB,CAAC;IAED,OAAO,EAAE,GAAG,CAAC,GAAG,CAAC,CAAA;AACrB,CAAC,CAAA;AAUD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,GAAQ,EAAE,MAAc,EAAE,EAAE;IACnD,OAAO,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAA;AACxC,CAAC,CAAA"}

View File

@ -0,0 +1,7 @@
import { add } from './utils';
const a: number = 1;
const b: number = 2;
const c = 3;
console.info(add(a, b))

View File

@ -0,0 +1,25 @@
export const add = (a: number, b: number) => {
if (a > 0) {
return a + b
}
return '' + a + b
}
interface Cat {
name?: {
fistName: string;
lastName: string;
age: number;
}
}
/**
* getCatName в консоль.
*
* @param {Cat} cat Сообщение.
* @param {number} notCat Тип сообщения.
*/
export const getCatName = (cat: Cat, notCat: number) => {
return cat.name && cat.name.fistName
}

4
03_more_options/test.js Normal file
View File

@ -0,0 +1,4 @@
// @ts-check
import { add } from './dist/utils'
add(1, '2')

View File

@ -0,0 +1,32 @@
{
"compilerOptions": {
/* Basic Options */
"target": "ESNext", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "ESNext", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
"outDir": "dist", /* Redirect output structure to the directory. */
// "noEmit": true, /* Do not emit outputs. */
/* Strict Type-Checking Options */
"strict": false, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictNullChecks": true, /* Enable strict null checks. */
/* Additional Checks */
"noUnusedLocals": false, /* Report errors on unused locals. */
"noUnusedParameters": false, /* Report errors on unused parameters. */
"noImplicitReturns": false, /* Report error when not all code paths in function return a value. */
/* Source Map Options */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
},
"files": [
"src/index.ts"
],
"exclude": [
"node_modules",
"**/*.ts"
]
}

16
04_lint/eslint.config.mjs Normal file
View File

@ -0,0 +1,16 @@
import globals from 'globals';
import pluginJs from '@eslint/js';
import tseslint from 'typescript-eslint';
export default [
{files: ['**/*.{js,mjs,cjs,ts}']},
{languageOptions: { globals: globals.browser }},
pluginJs.configs.recommended,
...tseslint.configs.recommended,
{
rules: {
quotes: ['error', 'single'],
}
}
];

8
04_lint/example.ts Normal file
View File

@ -0,0 +1,8 @@
const boys = 32;
const girls = 25;
const summ = (a, b) => {
return a + b;
}
const boysAndGirls = summ(boys, girls);

1597
04_lint/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

18
04_lint/package.json Normal file
View File

@ -0,0 +1,18 @@
{
"name": "04_lint",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@eslint/js": "^9.12.0",
"eslint": "^9.12.0",
"globals": "^15.10.0",
"typescript-eslint": "^8.8.1"
}
}

6
04_lint/src/index.ts Normal file
View File

@ -0,0 +1,6 @@
import { logger } from './utils';
import { MESSAGE_TYPE } from "./model";
logger('good');
logger("something is wrong", MESSAGE_TYPE.WARNING)
logger('something is very wrong', MESSAGE_TYPE.ERROR);

View File

@ -0,0 +1,12 @@
/**
* Тип сообщения.
*
* WARNING - Предупреждение.
* ERROR - Ошибка.
* SUCCESS - Успешно.
*/
export enum MESSAGE_TYPE {
WARNING = '#EA9325',
ERROR = '#FF3532',
SUCCESS = '#449D2C'
}

View File

@ -0,0 +1,2 @@
export { MESSAGE_TYPE } from './enums';
export { TMessage } from './types';

View File

@ -0,0 +1,4 @@
/**
* Сообщение.
*/
export type TMessage = string | number;

View File

@ -0,0 +1 @@
export { logger } from './logUtils';

View File

@ -0,0 +1,14 @@
import { TMessage, MESSAGE_TYPE } from '../model';
/**
* Логирует цветное сообщение в консоль.
*
* @param {TMessage} message Сообщение.
* @param {MESSAGE_TYPE} type Тип сообщения.
*/
export const logger = (message: TMessage, type: MESSAGE_TYPE = MESSAGE_TYPE.SUCCESS): void => {
console.info(`%c ${message}`, `
color: ${type};
font-size: 25px;
`);
};

40
05_error/animals.js Normal file
View File

@ -0,0 +1,40 @@
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Animal = /** @class */ (function () {
function Animal() {
}
return Animal;
}());
var Dog = /** @class */ (function (_super) {
__extends(Dog, _super);
function Dog() {
return _super !== null && _super.apply(this, arguments) || this;
}
Dog.prototype.bark = function () { };
return Dog;
}(Animal));
var Cat = /** @class */ (function (_super) {
__extends(Cat, _super);
function Cat() {
return _super !== null && _super.apply(this, arguments) || this;
}
Cat.prototype.meow = function () { };
return Cat;
}(Animal));
var cage1 = [new Dog(), new Dog()];
var cage2 = cage1; // ok
cage2.push(new Cat()); // ok
cage1.forEach(function (dog) { return dog.bark(); }); // ok

11
05_error/animals.ts Normal file
View File

@ -0,0 +1,11 @@
class Animal {}
class Dog extends Animal { bark() {} }
class Cat extends Animal { meow() {} }
const cage1 = [new Dog(), new Dog()];
const cage2: Animal[] = cage1; // ok
cage2.push(new Cat()); // ok
cage1.forEach(dog => dog.bark()) // ok

5
05_error/links.md Normal file
View File

@ -0,0 +1,5 @@
# Links
- [Javascript Abstract Syntax Tree](https://www.jointjs.com/demos/abstract-syntax-tree)
- [ast explorer](https://astexplorer.net/)
- [ts ast viewer](https://ts-ast-viewer.com/#)

110
05_error/tsconfig.json Normal file
View File

@ -0,0 +1,110 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "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. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "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. */
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

17
06_complex/infer.ts Normal file
View File

@ -0,0 +1,17 @@
const arr = [1, 2, '3', 4, 5];
// get type of array
type GetArrItem<Arg> = Arg extends (infer Item)[] ? Item : never;
type ArrItem = GetArrItem<typeof arr>
const user = { name: 'John', age: 30 } as const;
// get type of name property
type GetObjectNameType<Name> = Name extends { name: infer T } ? T : never
type UserName = GetObjectNameType<typeof user>
const double = (x: number, s: 'foo') => x * 2;
// get type of first argument of function
type GetFirstFuncArg<Arg> = Arg extends (a, x: infer T) => any ? T : never;
type DoubleArgType = GetFirstFuncArg<typeof double>

BIN
assets/01.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB