├── .gitignore ├── .gitpod.yml ├── .vscode ├── launch.json └── settings.json ├── babel.config.js ├── jest.config.ts ├── package-lock.json ├── package.json ├── slides.pdf ├── src ├── javascript │ ├── conteudo │ │ ├── arrays.ts │ │ ├── declaracoes.ts │ │ ├── destrutores.ts │ │ ├── exports.ts │ │ ├── funcoes.ts │ │ ├── imports.ts │ │ ├── loops.ts │ │ ├── primitivas-e-wrappers.ts │ │ ├── promises.ts │ │ ├── shorthands.ts │ │ ├── switch-case.ts │ │ └── template-strings.ts │ └── exercicios │ │ ├── exercicios-javascript.spec.ts │ │ └── exercicios-javascript.ts └── typescript │ ├── conteudo │ ├── as-const.ts │ ├── classes.ts │ ├── enums.ts │ ├── interfaces-tipos.ts │ ├── modificadores.ts │ ├── strict-null-checks.ts │ ├── tipos-basicos.ts │ ├── tipos-especiais.ts │ ├── tipos-literais.ts │ └── unioes.ts │ └── exercicios │ ├── interfaces.ts │ ├── tipos-basicos.ts │ └── uniao.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | dist 4 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | tasks: 2 | - init: yarn install 3 | command: yarn test 4 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "launch", 10 | "name": "Debug File", 11 | "program": "${file}", 12 | "skipFiles": [ 13 | "/**", 14 | "node_modules/ts-node/**" 15 | ], 16 | "runtimeArgs": [ 17 | "-r", 18 | "ts-node/register" 19 | // "--loader", 20 | // "ts-node/esm" 21 | ] 22 | }, 23 | ] 24 | } 25 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.locale": "pt-BR", 3 | "editor.formatOnSave": true, 4 | "workbench.colorTheme": "Default Dark+", 5 | "js/ts.implicitProjectConfig.strictNullChecks": true 6 | } 7 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | ['@babel/preset-env', {targets: {node: 'current'}}], 4 | '@babel/preset-typescript' 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /jest.config.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * For a detailed explanation regarding each configuration property and type check, visit: 3 | * https://jestjs.io/docs/configuration 4 | */ 5 | 6 | export default { 7 | // All imported modules in your tests should be mocked automatically 8 | // automock: false, 9 | 10 | // Stop running tests after `n` failures 11 | // bail: 0, 12 | 13 | // The directory where Jest should store its cached dependency information 14 | // cacheDirectory: "C:\\Users\\Desktop\\AppData\\Local\\Temp\\jest", 15 | 16 | // Automatically clear mock calls and instances between every test 17 | clearMocks: true, 18 | 19 | // Indicates whether the coverage information should be collected while executing the test 20 | collectCoverage: true, 21 | 22 | // An array of glob patterns indicating a set of files for which coverage information should be collected 23 | // collectCoverageFrom: undefined, 24 | 25 | // The directory where Jest should output its coverage files 26 | coverageDirectory: "coverage", 27 | 28 | // An array of regexp pattern strings used to skip coverage collection 29 | // coveragePathIgnorePatterns: [ 30 | // "\\\\node_modules\\\\" 31 | // ], 32 | 33 | // Indicates which provider should be used to instrument code for coverage 34 | coverageProvider: "v8", 35 | 36 | // A list of reporter names that Jest uses when writing coverage reports 37 | // coverageReporters: [ 38 | // "json", 39 | // "text", 40 | // "lcov", 41 | // "clover" 42 | // ], 43 | 44 | // An object that configures minimum threshold enforcement for coverage results 45 | // coverageThreshold: undefined, 46 | 47 | // A path to a custom dependency extractor 48 | // dependencyExtractor: undefined, 49 | 50 | // Make calling deprecated APIs throw helpful error messages 51 | // errorOnDeprecated: false, 52 | 53 | // Force coverage collection from ignored files using an array of glob patterns 54 | // forceCoverageMatch: [], 55 | 56 | // A path to a module which exports an async function that is triggered once before all test suites 57 | // globalSetup: undefined, 58 | 59 | // A path to a module which exports an async function that is triggered once after all test suites 60 | // globalTeardown: undefined, 61 | 62 | // A set of global variables that need to be available in all test environments 63 | // globals: {}, 64 | 65 | // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. 66 | // maxWorkers: "50%", 67 | 68 | // An array of directory names to be searched recursively up from the requiring module's location 69 | // moduleDirectories: [ 70 | // "node_modules" 71 | // ], 72 | 73 | // An array of file extensions your modules use 74 | // moduleFileExtensions: [ 75 | // "js", 76 | // "jsx", 77 | // "ts", 78 | // "tsx", 79 | // "json", 80 | // "node" 81 | // ], 82 | 83 | // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module 84 | // moduleNameMapper: {}, 85 | 86 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 87 | // modulePathIgnorePatterns: [], 88 | 89 | // Activates notifications for test results 90 | // notify: false, 91 | 92 | // An enum that specifies notification mode. Requires { notify: true } 93 | // notifyMode: "failure-change", 94 | 95 | // A preset that is used as a base for Jest's configuration 96 | // preset: undefined, 97 | 98 | // Run tests from one or more projects 99 | // projects: undefined, 100 | 101 | // Use this configuration option to add custom reporters to Jest 102 | // reporters: undefined, 103 | 104 | // Automatically reset mock state between every test 105 | // resetMocks: false, 106 | 107 | // Reset the module registry before running each individual test 108 | // resetModules: false, 109 | 110 | // A path to a custom resolver 111 | // resolver: undefined, 112 | 113 | // Automatically restore mock state between every test 114 | // restoreMocks: false, 115 | 116 | // The root directory that Jest should scan for tests and modules within 117 | // rootDir: undefined, 118 | 119 | // A list of paths to directories that Jest should use to search for files in 120 | // roots: [ 121 | // "" 122 | // ], 123 | 124 | // Allows you to use a custom runner instead of Jest's default test runner 125 | // runner: "jest-runner", 126 | 127 | // The paths to modules that run some code to configure or set up the testing environment before each test 128 | // setupFiles: [], 129 | 130 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 131 | // setupFilesAfterEnv: [], 132 | 133 | // The number of seconds after which a test is considered as slow and reported as such in the results. 134 | // slowTestThreshold: 5, 135 | 136 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 137 | // snapshotSerializers: [], 138 | 139 | // The test environment that will be used for testing 140 | // testEnvironment: "jest-environment-node", 141 | 142 | // Options that will be passed to the testEnvironment 143 | // testEnvironmentOptions: {}, 144 | 145 | // Adds a location field to test results 146 | // testLocationInResults: false, 147 | 148 | // The glob patterns Jest uses to detect test files 149 | // testMatch: [ 150 | // "**/__tests__/**/*.[jt]s?(x)", 151 | // "**/?(*.)+(spec|test).[tj]s?(x)" 152 | // ], 153 | 154 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 155 | // testPathIgnorePatterns: [ 156 | // "\\\\node_modules\\\\" 157 | // ], 158 | 159 | // The regexp pattern or array of patterns that Jest uses to detect test files 160 | // testRegex: [], 161 | 162 | // This option allows the use of a custom results processor 163 | // testResultsProcessor: undefined, 164 | 165 | // This option allows use of a custom test runner 166 | // testRunner: "jest-circus/runner", 167 | 168 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href 169 | // testURL: "http://localhost", 170 | 171 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" 172 | // timers: "real", 173 | 174 | // A map from regular expressions to paths to transformers 175 | // transform: undefined, 176 | 177 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 178 | // transformIgnorePatterns: [ 179 | // "\\\\node_modules\\\\", 180 | // "\\.pnp\\.[^\\\\]+$" 181 | // ], 182 | 183 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 184 | // unmockedModulePathPatterns: undefined, 185 | 186 | // Indicates whether each individual test should be reported during the run 187 | // verbose: undefined, 188 | 189 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 190 | // watchPathIgnorePatterns: [], 191 | 192 | // Whether to use watchman for file crawling 193 | // watchman: true, 194 | }; 195 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "devschool-1-typescript", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "dev": "tsc --watch", 8 | "test": "jest --watch" 9 | }, 10 | "author": "Alan Jhonnes ", 11 | "license": "MIT", 12 | "devDependencies": { 13 | "@babel/core": "^7.17.5", 14 | "@babel/preset-env": "^7.16.11", 15 | "@babel/preset-typescript": "^7.16.7", 16 | "@types/jest": "^27.4.1", 17 | "babel-jest": "^27.5.1", 18 | "jest": "^27.5.1", 19 | "ts-node": "^10.5.0", 20 | "typescript": "^4.5.5" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /slides.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alanjhonnes/devschool-typescript/a89cd2562e10e09a3bc9db1e73ae8d843883174f/slides.pdf -------------------------------------------------------------------------------- /src/javascript/conteudo/arrays.ts: -------------------------------------------------------------------------------- 1 | 2 | const arrayNumeros = [1, 2, 3, 4, 5]; 3 | 4 | const arrayDeObjetos = [ 5 | { nome: 'Alan', }, 6 | { nome: 'Nathan', }, 7 | ] 8 | 9 | const matriz2d = [ 10 | [1, 2, 3], 11 | [4, 5, 6], 12 | [4, 5, 6], 13 | [4, 5, 6], 14 | [4, 5, 6], 15 | [4, 5, 6], 16 | ] 17 | 18 | const dobroNumeros = arrayNumeros 19 | .map(x => x * 2); 20 | 21 | const numerosComoStrings = arrayNumeros 22 | .map(x => x.toString()); 23 | 24 | const listaDeNomes = arrayDeObjetos 25 | .map(pessoa => pessoa.nome); 26 | 27 | const nomesQueComecamComA = listaDeNomes 28 | .filter(nome => nome.startsWith('A')); 29 | 30 | const totalNumeros = arrayNumeros 31 | .reduce((acumulador, valorAtual) => { 32 | 33 | return acumulador + valorAtual 34 | }, 0) 35 | 36 | const arrayNumeros2 = arrayNumeros.concat() 37 | 38 | export const pessoa = arrayDeObjetos.find(pessoa => pessoa.nome === 'Aldfgfdgan'); 39 | 40 | console.log(pessoa) 41 | -------------------------------------------------------------------------------- /src/javascript/conteudo/declaracoes.ts: -------------------------------------------------------------------------------- 1 | // Declaração de variáveis 2 | 3 | // "let" possibilita a alteração da variável 4 | export let a: number; 5 | 6 | a = 10; 7 | a = 20; 8 | 9 | // Declarações de constantes não podem sofrer alteração posteriormente, então precisam ser inicializadas com um valor 10 | const x = 5; 11 | // Inicializações de valores básicos: 12 | 13 | if (true) { 14 | let y = 10 15 | 16 | y = 20 17 | 18 | const b = a + y 19 | } 20 | 21 | const str = 'string'; 22 | let string2 = 'string' 23 | 24 | const str2 = str + string2 25 | 26 | if (str === string2) { 27 | 28 | } 29 | 30 | const valor1: any = 0 31 | const valor2: any = "0" 32 | 33 | if (valor1 === valor2) { 34 | console.log(true) 35 | } 36 | 37 | const nbr = 1234.5678 38 | 39 | const nul = null; 40 | 41 | const undef = undefined; 42 | 43 | const array = []; 44 | 45 | const arrayComValores = [1, 2, 3, '']; 46 | 47 | const array2d = [ 48 | [1, 2, 3], 49 | [4, 5, 6], 50 | ] 51 | 52 | const objeto: any = { 53 | a: null 54 | }; 55 | 56 | console.log(objeto.a) 57 | 58 | const objetoComPropriedades = { 59 | nome: 'valor', 60 | turma: 1, 61 | } 62 | 63 | -------------------------------------------------------------------------------- /src/javascript/conteudo/destrutores.ts: -------------------------------------------------------------------------------- 1 | const objetoParaDestruturar = { 2 | nome: 'Alan', 3 | numero: 1, 4 | } 5 | 6 | const nomeObjeto = objetoParaDestruturar.nome; 7 | const numerobjeto = objetoParaDestruturar.numero; 8 | 9 | const { nome: nomes = "", numero: numeroxpto } = objetoParaDestruturar; 10 | nomes 11 | numeroxpto 12 | 13 | // renomeando para variáveis diferentes 14 | const { nome: nomeAlias, numero: numeroAlias } = objetoParaDestruturar; 15 | 16 | const arrayParaDestruturar = [1, 2, 3, 4, 5] as const; 17 | 18 | const [um, dois, tres, ...resto] = arrayParaDestruturar; 19 | 20 | um 21 | dois 22 | tres 23 | resto 24 | -------------------------------------------------------------------------------- /src/javascript/conteudo/exports.ts: -------------------------------------------------------------------------------- 1 | export const export1 = "xpto" 2 | 3 | export function funcaoUtilitaria() { 4 | 5 | } 6 | 7 | export interface Pessoa { 8 | nome: string 9 | } 10 | 11 | export default export1 12 | -------------------------------------------------------------------------------- /src/javascript/conteudo/funcoes.ts: -------------------------------------------------------------------------------- 1 | function funcaoComNome() { 2 | return 0; 3 | } 4 | 5 | // funcoes anonimas podem ser atribuidas a variáveis 6 | const funcao = function () { 7 | return 1; 8 | } 9 | 10 | // funcoes anonimas (em formato arrow-function) podem ser atribuidas a variáveis 11 | const arrowFn = () => { 12 | const a = 5; 13 | 14 | return () => { 15 | a 16 | const b = 10 17 | return b 18 | } 19 | } 20 | 21 | const x = arrowFn() 22 | 23 | -------------------------------------------------------------------------------- /src/javascript/conteudo/imports.ts: -------------------------------------------------------------------------------- 1 | import { Pessoa, funcaoUtilitaria, export1 } from './exports' 2 | 3 | const x = export1 4 | -------------------------------------------------------------------------------- /src/javascript/conteudo/loops.ts: -------------------------------------------------------------------------------- 1 | const vetor = [1, 2]; 2 | const tamanhoVetor = vetor.length; 3 | for (let i = 0; i < tamanhoVetor; i++) { 4 | console.log(i); 5 | const val = vetor[i] 6 | console.log(val) 7 | } 8 | 9 | let j = 0; 10 | let pessoaEncontrada = false 11 | while (j < 5) { 12 | pessoaEncontrada = true; 13 | console.log(j); 14 | j++ 15 | } 16 | 17 | let k = 0; 18 | do { 19 | k++; 20 | console.log(k); 21 | continue; 22 | console.log(k); 23 | } 24 | while (k < 10); 25 | 26 | // 27 | let h = 0; 28 | let l = 0; 29 | 30 | while (h < 10) { 31 | h++; 32 | if (h === 5) { 33 | continue; 34 | } 35 | labelWhile: 36 | while (l < 5) { 37 | l++; 38 | if (h === 2) { 39 | break labelWhile; 40 | } 41 | } 42 | } 43 | 44 | 45 | const objetoParaIterar = { 46 | propriedade1: 1, 47 | propriedade2: 2, 48 | propriedade3: 3, 49 | } 50 | 51 | for (let propriedade in objetoParaIterar) { 52 | console.log(`propriedade do objeto: ${propriedade}`); 53 | const val = objetoParaIterar[propriedade] 54 | } 55 | 56 | const listaParaIterar = [1, 2, 3]; 57 | 58 | for (let valorDaLista of listaParaIterar) { 59 | console.log(`valor da lista: ${valorDaLista}`); 60 | } 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /src/javascript/conteudo/primitivas-e-wrappers.ts: -------------------------------------------------------------------------------- 1 | // Primitivas 2 | let primitivaString = 'string'; 3 | 4 | let primitivaNumber = 1234; 5 | 6 | let primitivaBigInt = 123456789012345678901234567890n; 7 | 8 | let primitivaBoolean = true; 9 | 10 | let primitivaSymbol = Symbol("xpto"); 11 | let primitivaSymbol2 = Symbol("xpto"); 12 | 13 | if (primitivaSymbol === primitivaSymbol2) { 14 | console.log(true) 15 | } 16 | 17 | const primitivaUndefined = undefined; 18 | 19 | const primitivaNull = null; 20 | 21 | // Wrappers primitivos 22 | 23 | primitivaString.toUpperCase(); 24 | 25 | primitivaNumber.toFixed(2); 26 | 27 | primitivaBigInt.toString(); 28 | 29 | primitivaBoolean.valueOf(); 30 | 31 | primitivaSymbol.description; 32 | -------------------------------------------------------------------------------- /src/javascript/conteudo/promises.ts: -------------------------------------------------------------------------------- 1 | let result; 2 | 3 | const minhaPromise = new Promise((resolve, reject) => { 4 | setTimeout(() => resolve(('resultado')), 1000); 5 | }) 6 | console.log("um") 7 | minhaPromise.then(value => { 8 | console.log(value) 9 | console.log("tres") 10 | }) 11 | minhaPromise.catch(error => { 12 | console.log(error) 13 | }) 14 | console.log("dois") 15 | 16 | // console.log(result); 17 | 18 | async function fn() { 19 | return 10 20 | } 21 | 22 | async function programa() { 23 | const x = await fn() 24 | } 25 | 26 | async function funcaoAsync() { 27 | const resultado = await minhaPromise; 28 | console.log(resultado); 29 | const resultado2 = await new Promise((resolve, reject) => { 30 | setTimeout(() => resolve('resultado2'), 5000); 31 | }); 32 | console.log(resultado2); 33 | return resultado + resultado2; 34 | } 35 | 36 | function funcaoAsync2() { 37 | return new Promise(resolve => { 38 | return resolve(minhaPromise) 39 | }) 40 | .then(resultado1 => { 41 | return new Promise((resolve, reject) => { 42 | setTimeout(() => resolve('resultado2'), 5000); 43 | }) 44 | .then(resultado2 => { 45 | return resultado1 + resultado2; 46 | }); 47 | }) 48 | .then(final => { 49 | console.log(final) 50 | return final 51 | }) 52 | 53 | } 54 | 55 | funcaoAsync2().then(resultado => { 56 | console.log(resultado) 57 | }) 58 | 59 | funcaoAsync() 60 | .then((total) => { 61 | console.log(total); 62 | }); 63 | 64 | // minhaPromise 65 | // .then(resultado => { 66 | // result = resultado; 67 | // console.log(resultado) // vai printar 'resultado' após 1 segundo 68 | 69 | // return 70 | // }) 71 | // .then(resultado2 => { 72 | // console.log(resultado2); 73 | // }) 74 | 75 | // console.log(result); 76 | 77 | 78 | -------------------------------------------------------------------------------- /src/javascript/conteudo/shorthands.ts: -------------------------------------------------------------------------------- 1 | // Shorthand de Arrow functions 2 | 3 | const myArrowFn = (a, b) => { 4 | return; 5 | }; 6 | 7 | const myArrowFnShorthand = (a, b) => ({ a: 10 }); 8 | const myArrowFnObjeto = () => ({ 9 | resultado: 'valor' 10 | }); 11 | 12 | 13 | const myArrowFnObjetoShorthand = () => ( 14 | { 15 | resultado: 'result' 16 | } 17 | ); 18 | 19 | 20 | const arrowFnComUmArgumento = x => x * 2; 21 | 22 | let prop1 = 'a'; 23 | let prop2 = 'b'; 24 | 25 | const inicializadorDeObjeto = { 26 | prop1: prop1, 27 | prop2: prop2, 28 | metodo: function (arg) { 29 | console.log(arg) 30 | } 31 | } 32 | 33 | inicializadorDeObjeto.metodo('xpto'); 34 | 35 | const inicializadorDeObjetoShorthand = { 36 | prop1, 37 | prop2, 38 | metodo(arg) { 39 | console.log(arg) 40 | }, 41 | } 42 | 43 | const duplicacaoDeObjetoComSpread = { 44 | ...inicializadorDeObjeto, 45 | propriedade: "alan" 46 | } 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/javascript/conteudo/switch-case.ts: -------------------------------------------------------------------------------- 1 | function switchTest(switchVar: string) { 2 | switch (switchVar) { 3 | case 'case1': { 4 | console.log('case1'); 5 | break; 6 | } 7 | case 'case2': { 8 | console.log('case2'); 9 | break; 10 | } 11 | default: { 12 | console.log('default'); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/javascript/conteudo/template-strings.ts: -------------------------------------------------------------------------------- 1 | const minhaTemplateString = `minha string`; 2 | 3 | const templateStringInterpolada = `interpolada: ${minhaTemplateString}` 4 | -------------------------------------------------------------------------------- /src/javascript/exercicios/exercicios-javascript.spec.ts: -------------------------------------------------------------------------------- 1 | import { elevarAoQuadrado, somaNumeros, somentePares } from "./exercicios-javascript"; 2 | 3 | describe("Exercicios Javascript", () => { 4 | 5 | describe("Somente pares", () => { 6 | it("Deve retornar somente os números pares dado um determinado vetor", () => { 7 | const input = [1, 2, 3, 4]; 8 | const result = [2, 4]; 9 | expect(somentePares(input)).toEqual(result); 10 | }) 11 | }); 12 | 13 | describe("Soma total", () => { 14 | it("Deve retornar a soma de todos os items do array", () => { 15 | const input = [1, 2, 3, 4]; 16 | const result = 10; 17 | expect(somaNumeros(input)).toEqual(result); 18 | }) 19 | }); 20 | 21 | describe("Elevar ao quadrado", () => { 22 | it("Deve retornar o quadrado de cada item do array", () => { 23 | const input = [1, 2, 3, 4]; 24 | const result = [1, 4, 9, 16]; 25 | expect(elevarAoQuadrado(input)).toEqual(result); 26 | }) 27 | }); 28 | }) 29 | -------------------------------------------------------------------------------- /src/javascript/exercicios/exercicios-javascript.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Faça a função retornar um array somente com os números pares 3 | * @param numeros 4 | */ 5 | export function somentePares(numeros: number[]): number[] { 6 | return numeros; 7 | } 8 | 9 | console.log(somentePares([1, 2, 3, 4])); 10 | 11 | /** 12 | * Complete a função para retornar a soma de todos os números do vetor 13 | * @param numeros 14 | */ 15 | export function somaNumeros(numeros: number[]): number { 16 | return 0; 17 | } 18 | 19 | somaNumeros([1, 2, 3, 4, 5]) 20 | 21 | /** 22 | * Complete a função para retornar um vetor com o quadrado de cada valor 23 | * @param numeros 24 | */ 25 | export function elevarAoQuadrado(numeros: number[]): number[] { 26 | return numeros; 27 | } 28 | 29 | console.log(elevarAoQuadrado([1, 2, 3, 4])); 30 | -------------------------------------------------------------------------------- /src/typescript/conteudo/as-const.ts: -------------------------------------------------------------------------------- 1 | const bigConfigObject = { 2 | url: "http://api.localhost", 3 | options: { 4 | retries: 2, 5 | agent: { 6 | https: false, 7 | } 8 | }, 9 | sequence: [1, 2, 3], 10 | commands: { 11 | NEXT: 1, 12 | START: 2 13 | } 14 | } as const; 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/typescript/conteudo/classes.ts: -------------------------------------------------------------------------------- 1 | class MinhaClasse { 2 | 3 | // propriedade privada via javascript 4 | #_propriedade = 100; 5 | 6 | // propriedade pseudo-privada via typescript 7 | private privada = 200; 8 | 9 | // propriedade protegida via typescript 10 | protected protegida = 300; 11 | 12 | // propriedade publicas 13 | publica1 = 1; 14 | public publica2 = 2; 15 | 16 | // propriedades podem ser declaradas no construtor para evitar repetição 17 | constructor(public publica3 = 3) { 18 | } 19 | 20 | metodo() { 21 | return this.#_propriedade * 100; 22 | } 23 | 24 | get propriedade() { 25 | return this.#_propriedade; 26 | } 27 | 28 | set propriedade(valor: number) { 29 | this.#_propriedade = valor; 30 | } 31 | } 32 | 33 | function classFn(klass: MinhaClasse) { 34 | // klass.; 35 | } 36 | 37 | const minhaClasse = new MinhaClasse(3); 38 | minhaClasse.publica3 39 | -------------------------------------------------------------------------------- /src/typescript/conteudo/enums.ts: -------------------------------------------------------------------------------- 1 | export enum ACTION { 2 | PLAY = '1', 3 | PAUSE = '2', 4 | STOP = '3', 5 | } 6 | 7 | function doAction(action: ACTION) { 8 | console.log(action); 9 | } 10 | 11 | doAction(ACTION.PLAY) 12 | -------------------------------------------------------------------------------- /src/typescript/conteudo/interfaces-tipos.ts: -------------------------------------------------------------------------------- 1 | export interface Pessoa { 2 | nome: string; 3 | idade: number; 4 | } 5 | 6 | export type Pessoa2 = { 7 | nome: string; 8 | idade: number; 9 | } 10 | -------------------------------------------------------------------------------- /src/typescript/conteudo/modificadores.ts: -------------------------------------------------------------------------------- 1 | export interface User { 2 | readonly id: string; 3 | name: string; 4 | email?: string; 5 | } 6 | 7 | const user: User = { 8 | id: "1234", 9 | name: "Alan Jhonnes", 10 | }; 11 | 12 | user.name = "Alan"; 13 | // user.id = "4321"; 14 | 15 | if (user.email) { 16 | user.email.toUpperCase(); 17 | } 18 | -------------------------------------------------------------------------------- /src/typescript/conteudo/strict-null-checks.ts: -------------------------------------------------------------------------------- 1 | export const x = undefined; 2 | 3 | export const y = null; 4 | -------------------------------------------------------------------------------- /src/typescript/conteudo/tipos-basicos.ts: -------------------------------------------------------------------------------- 1 | export let str: string = ""; 2 | 3 | export let numbr: number = 10; 4 | 5 | export const alan = "alan" 6 | 7 | export let fn = function () { 8 | return true; 9 | }; 10 | 11 | export const arr: string[] = []; 12 | 13 | export type Pessoa = { 14 | nome: string; 15 | idade: number; 16 | } 17 | 18 | export const pessoa: Pessoa = { 19 | nome: 'dfg', 20 | idade: 1 21 | } 22 | 23 | export type Tupla = [string, number] 24 | 25 | const tupla: Tupla = ['1', 1]; 26 | 27 | 28 | export type FuncaoSoma = (a: number, b: number) => number; 29 | 30 | export const typedFn: FuncaoSoma = (a, b) => { 31 | return a + b; 32 | } 33 | -------------------------------------------------------------------------------- /src/typescript/conteudo/tipos-especiais.ts: -------------------------------------------------------------------------------- 1 | export const anything: any = 2; 2 | 3 | export const idk: unknown = {}; 4 | 5 | export function noReturn(): void { 6 | return; 7 | } 8 | 9 | function alwaysThrows(): never { 10 | // while (true) { 11 | 12 | // } 13 | throw new Error(); 14 | } 15 | 16 | if (idk === undefined) { 17 | idk 18 | } 19 | 20 | if (idk instanceof Date) { 21 | idk 22 | } 23 | -------------------------------------------------------------------------------- /src/typescript/conteudo/tipos-literais.ts: -------------------------------------------------------------------------------- 1 | const alan = "Alan"; 2 | const id = 1; 3 | 4 | type YesOrNo = "y" | "n"; 5 | 6 | const alwaysTrue: false = false; 7 | 8 | function shouldContinue(input: YesOrNo): boolean { 9 | if (input === "y") { 10 | return true; 11 | } 12 | return false; 13 | } 14 | 15 | type Generico = { 16 | item: TipoItem, 17 | nome: TipoNome 18 | } 19 | 20 | const generico: Generico<1 | 2 | 3> = { 21 | item: 2, 22 | nome: 'nome' 23 | } 24 | -------------------------------------------------------------------------------- /src/typescript/conteudo/unioes.ts: -------------------------------------------------------------------------------- 1 | export type Bool = true | false; 2 | 3 | 4 | export interface User { 5 | id: string; 6 | name: string; 7 | } 8 | 9 | export type PossibleUser = User | null; 10 | 11 | export function isAnonymous(currentUser: PossibleUser): boolean { 12 | return currentUser === null; 13 | } 14 | -------------------------------------------------------------------------------- /src/typescript/exercicios/interfaces.ts: -------------------------------------------------------------------------------- 1 | // Crie uma interface para representar cada um dos objetos abaixo e coloque o tipo apropriado para cada uma das constantes. 2 | 3 | const linguagem = { 4 | nome: 'Typescript', 5 | tipada: true, 6 | } 7 | 8 | const pessoa = { 9 | nome: 'Alan', 10 | sobrenome: 'Jhonnes', 11 | idade: 31, 12 | amigos: [ 13 | { 14 | nome: 'Nathan', 15 | sobrenome: 'Lima', 16 | idade: 22, 17 | amigos: [], 18 | } 19 | ] 20 | } 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/typescript/exercicios/tipos-basicos.ts: -------------------------------------------------------------------------------- 1 | // Complete as funções com os tipos apropriados 2 | 3 | function soma(a, b) { 4 | return a + b; 5 | } 6 | 7 | function concatenaPalavras(palavra1, palavra2) { 8 | return palavra1.concat(palavra2) 9 | } 10 | 11 | function tamanhoDoVetor(vetor) { 12 | return vetor.length; 13 | } 14 | -------------------------------------------------------------------------------- /src/typescript/exercicios/uniao.ts: -------------------------------------------------------------------------------- 1 | // Crie um novo tipo "StringOuNumero" utilizando união de tipo 2 | 3 | export type StringOuNumero = any; 4 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "locale": "pt", 4 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 5 | /* Basic Options */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | "target": "es2020", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */ 8 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 9 | // "lib": [], /* Specify library files to be included in the compilation. */ 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ 13 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | "outDir": "./dist", /* Redirect output structure to the directory. */ 18 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 | // "removeComments": true, /* Do not emit comments to output. */ 22 | // "noEmit": true, /* Do not emit outputs. */ 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | /* Strict Type-Checking Options */ 27 | "strict": true, /* Enable all strict type-checking options. */ 28 | "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */ 29 | // "strictNullChecks": true, /* Enable strict null checks. */ 30 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 31 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 32 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 33 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 34 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 35 | /* Additional Checks */ 36 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 37 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 38 | "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 39 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 40 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 41 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */ 42 | // "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */ 43 | /* Module Resolution Options */ 44 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 45 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 46 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 47 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 48 | // "typeRoots": [], /* List of folders to include type definitions from. */ 49 | // "types": [], /* Type declaration files to be included in compilation. */ 50 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 51 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 52 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 53 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 54 | /* Source Map Options */ 55 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 56 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 57 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 58 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 59 | /* Experimental Options */ 60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 62 | /* Advanced Options */ 63 | "noEmit": false, 64 | "skipLibCheck": true, /* Skip type checking of declaration files. */ 65 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 66 | } 67 | } 68 | --------------------------------------------------------------------------------