From 7adb9ee7c1a7911a3ba8b08925416ac50e60f6fd Mon Sep 17 00:00:00 2001 From: Guilherme Varandas Date: Wed, 9 Sep 2020 23:44:37 -0400 Subject: [PATCH 1/7] Add the original en file --- .../Generic Functions.ts | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts diff --git a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts new file mode 100644 index 000000000000..fbcfad44fbf4 --- /dev/null +++ b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts @@ -0,0 +1,100 @@ +// Generics provide a way to use Types as variables in other +// types. Meta. + +// We'll be trying to keep this example light, you can do +// a lot with generics and it's likely you will see some very +// complicated code using generics at some point - but that +// does not mean that generics are complicated. + +// Let's start with an example where we wrap an input object +// in an array. We will only care about one variable in this +// case, the type which was passed in: + +function wrapInArray(input: Type): Type[] { + return [input]; +} + +// Note: it's common to see Type referred to as T. This is +// culturally similar to how people use i in a for loop to +// represent index. T normally represents Type, so we'll +// be using the full name for clarity. + +// Our function will use inference to always keep the type +// passed in the same as the type passed out (though +// it will be wrapped in an array). + +const stringArray = wrapInArray("hello generics"); +const numberArray = wrapInArray(123); + +// We can verify this works as expected by checking +// if we can assign a string array to a function which +// should be an object array: +const notStringArray: string[] = wrapInArray({}); + +// You can also skip the generic inference by adding the +// type yourself also: +const stringArray2 = wrapInArray(""); + +// wrapInArray allows any type to be used, however there +// are cases when you need to only allow a subset of types. +// In these cases you can say the type has to extend a +// particular type. + +interface Drawable { + draw: () => void; +} + +// This function takes a set of objects which have a function +// for drawing to the screen +function renderToScreen(input: Type[]) { + input.forEach(i => i.draw()); +} + +const objectsWithDraw = [{ draw: () => {} }, { draw: () => {} }]; +renderToScreen(objectsWithDraw); + +// It will fail if draw is missing: + +renderToScreen([{}, { draw: () => {} }]); + +// Generics can start to look complicated when you have +// multiple variables. Here is an example of a caching +// function that lets you have different sets of input types +// and caches. + +interface CacheHost { + save: (a: any) => void; +} + +function addObjectToCache(obj: Type, cache: Cache): Cache { + cache.save(obj); + return cache; +} + +// This is the same as above, but with an extra parameter. +// Note: to make this work though, we had to use an any. This +// can be worked out by using a generic interface. + +interface CacheHostGeneric { + save: (a: ContentType) => void; +} + +// Now when the CacheHostGeneric is used, you need to tell +// it what ContentType is. + +function addTypedObjectToCache>(obj: Type, cache: Cache): Cache { + cache.save(obj); + return cache; +} + +// That escalated pretty quickly in terms of syntax. However, +// this provides more safety. These are trade-offs, that you +// have more knowledge to make now. When providing APIs for +// others, generics offer a flexible way to let others use +// their own types with full code inference. + +// For more examples of generics with classes and interfaces: +// +// example:advanced-classes +// example:typescript-with-react +// https://www.typescriptlang.org/docs/handbook/generics.html From 60f40c9a0730aa7c67535f417bacd669ce2f85f3 Mon Sep 17 00:00:00 2001 From: Guilherme Varandas Date: Thu, 10 Sep 2020 01:00:34 -0400 Subject: [PATCH 2/7] Translate the Generic Functions file to PT-BR --- .../Generic Functions.ts | 128 +++++++++--------- 1 file changed, 64 insertions(+), 64 deletions(-) diff --git a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts index fbcfad44fbf4..fa5d2f6b499a 100644 --- a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts +++ b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts @@ -1,99 +1,99 @@ -// Generics provide a way to use Types as variables in other -// types. Meta. +// Tipos genéricos provêm uma forma de usar Tipos como variáveis em outros +// tipos. Meta. -// We'll be trying to keep this example light, you can do -// a lot with generics and it's likely you will see some very -// complicated code using generics at some point - but that -// does not mean that generics are complicated. +// Tentaremos manter este exemplo leve. Você pode fazer +// muita coisa com tipos genéricos e é provável que veja algum código bem +// complicado usando tipos genéricos em algum ponto - mas isso +// não significa que tipos genéricos são complicados. -// Let's start with an example where we wrap an input object -// in an array. We will only care about one variable in this -// case, the type which was passed in: +// Vamos começar com um exemplo onde envolveremos um objeto de entrada +// em um array. Apenas nos importaremos com uma só variável neste +// caso: o tipo que foi passado como argumento: -function wrapInArray(input: Type): Type[] { - return [input]; +function envolverEmArray(entrada: Tipo): Tipo[] { + return [entrada]; } -// Note: it's common to see Type referred to as T. This is -// culturally similar to how people use i in a for loop to -// represent index. T normally represents Type, so we'll -// be using the full name for clarity. +// Nota: é comum ver Tipo ser referido como T. Isso é +// culturalmente similar à como as pessoas usam i em um loop for +// para representar índice. T normalmente representa Tipo, então +// usaremos o nome completo para maior clareza -// Our function will use inference to always keep the type -// passed in the same as the type passed out (though -// it will be wrapped in an array). +// Nossa função usará inferência para para sempre manter o tipo +// passado como argumento igual ao tipo retornado (porém +// envolvido em um array) -const stringArray = wrapInArray("hello generics"); -const numberArray = wrapInArray(123); +const stringArray = envolverEmArray("hello generics"); +const numberArray = envolverEmArray(123); -// We can verify this works as expected by checking -// if we can assign a string array to a function which -// should be an object array: -const notStringArray: string[] = wrapInArray({}); +// Podemos verificar que isso funciona como esperado ao checar +// se podemos atribuir um array de strings à uma função que +// deveria ser um array de objetos +const naoArrayDeStrings: string[] = envolverEmArray({}); -// You can also skip the generic inference by adding the -// type yourself also: -const stringArray2 = wrapInArray(""); +// Você também pode evitar a inferência adicionando +// o tipo você mesmo: +const arrayDeStrings2 = envolverEmArray(""); -// wrapInArray allows any type to be used, however there -// are cases when you need to only allow a subset of types. -// In these cases you can say the type has to extend a -// particular type. +// envolverEmArray permite que qualquer tipo seja usado, porém existem +// casos onde você precisa permitir apenas um subconjunto de tipos. +// Nesses casos você pode dizer que o tipo deve estender um +// tipo específico. -interface Drawable { - draw: () => void; +interface Desenhavel { + desenhar: () => void; } -// This function takes a set of objects which have a function -// for drawing to the screen -function renderToScreen(input: Type[]) { - input.forEach(i => i.draw()); +// Esta função receve um conjunto de objetos os quais possuem uma função +// para desenhar na tela +function renderizarNaTela(entrada: Tipo[]) { + entrada.forEach(i => i.desenhar()); } -const objectsWithDraw = [{ draw: () => {} }, { draw: () => {} }]; -renderToScreen(objectsWithDraw); +const objetosComDesenhar = [{ desenhar: () => {} }, { desenhar: () => {} }]; +renderizarNaTela(objetosComDesenhar); -// It will fail if draw is missing: +// Isso falhará se desenhar não estiver present: -renderToScreen([{}, { draw: () => {} }]); +renderizarNaTela([{}, { desenhar: () => {} }]); -// Generics can start to look complicated when you have -// multiple variables. Here is an example of a caching -// function that lets you have different sets of input types -// and caches. +// Tipos genéricos podem começar a parecer complicados quando você tem +// múltiplas variáveis. Aqui está um exemplo de uma função de caching +// que permite que você tenha diferentes conjuntos de tipos de entrada +// e caches. -interface CacheHost { - save: (a: any) => void; +interface HostDeCache { + salvar: (a: any) => void; } -function addObjectToCache(obj: Type, cache: Cache): Cache { - cache.save(obj); +function adicionarObjetoAoCache(obj: Tipo, cache: Cache): Cache { + cache.salvar(obj); return cache; } -// This is the same as above, but with an extra parameter. -// Note: to make this work though, we had to use an any. This -// can be worked out by using a generic interface. +// Este é o mesmo exemplo que acima, porém com um parâmetro extra. +// Nota: para fazê-lo funcionar, porém, tivemos que usar any. Isso +// pode ser resolvido usando uma interface genérica -interface CacheHostGeneric { - save: (a: ContentType) => void; +interface HostDeCacheGenerico { + salvar: (a: TipoDeConteudo) => void; } -// Now when the CacheHostGeneric is used, you need to tell -// it what ContentType is. +// Agora quando o HostDeCacheGenerico é usado, você deve dizer +// à dele qual é o TipoDeConteudo -function addTypedObjectToCache>(obj: Type, cache: Cache): Cache { - cache.save(obj); +function adicionarObjetoTipadoAoCache>(obj: Tipo, cache: Cache): Cache { + cache.salvar(obj); return cache; } -// That escalated pretty quickly in terms of syntax. However, -// this provides more safety. These are trade-offs, that you -// have more knowledge to make now. When providing APIs for -// others, generics offer a flexible way to let others use -// their own types with full code inference. +// O exemplo acima é bem intenso em termos de sintaxe. Porém, +// isso provê uma segurança maior. Estes são trade-offs (comprometimentos), +// os quais você agora possui conhecimento para fazer. Quando for prover APIs +// à outras pessoas, tipos genéricos oferecem um jeito flexível de permitir +// que elas usem seus próprios tipos sem ter que inferir seu código por completo. -// For more examples of generics with classes and interfaces: +// Para mais exemplos de tipos genéricos com classes e interfaces: // // example:advanced-classes // example:typescript-with-react From 6bfc48ea2702d78702ddf995a28b0619760cd0ff Mon Sep 17 00:00:00 2001 From: Guilherme Varandas Date: Thu, 10 Sep 2020 17:13:15 -0400 Subject: [PATCH 3/7] Update packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts Remove typo Co-authored-by: Danilo Campana Fuchs --- .../JavaScript/Functions with JavaScript/Generic Functions.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts index fa5d2f6b499a..c7c446b0c58d 100644 --- a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts +++ b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts @@ -19,7 +19,7 @@ function envolverEmArray(entrada: Tipo): Tipo[] { // para representar índice. T normalmente representa Tipo, então // usaremos o nome completo para maior clareza -// Nossa função usará inferência para para sempre manter o tipo +// Nossa função usará inferência para sempre manter o tipo // passado como argumento igual ao tipo retornado (porém // envolvido em um array) From 664760eabb904c40780d59f05b66f6fde81bcf83 Mon Sep 17 00:00:00 2001 From: Guilherme Varandas Date: Thu, 10 Sep 2020 17:16:40 -0400 Subject: [PATCH 4/7] Apply suggestions from code review Remove typos Co-authored-by: Danilo Campana Fuchs --- .../JavaScript/Functions with JavaScript/Generic Functions.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts index c7c446b0c58d..6218fed67604 100644 --- a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts +++ b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts @@ -53,7 +53,7 @@ function renderizarNaTela(entrada: Tipo[]) { const objetosComDesenhar = [{ desenhar: () => {} }, { desenhar: () => {} }]; renderizarNaTela(objetosComDesenhar); -// Isso falhará se desenhar não estiver present: +// Isso falhará se desenhar não estiver presente: renderizarNaTela([{}, { desenhar: () => {} }]); @@ -88,7 +88,7 @@ function adicionarObjetoTipadoAoCache Date: Fri, 18 Sep 2020 20:09:15 -0400 Subject: [PATCH 5/7] Address PR review changes --- .../Generic Functions.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts index 6218fed67604..b9bc21fb1b8b 100644 --- a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts +++ b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts @@ -15,8 +15,8 @@ function envolverEmArray(entrada: Tipo): Tipo[] { } // Nota: é comum ver Tipo ser referido como T. Isso é -// culturalmente similar à como as pessoas usam i em um loop for -// para representar índice. T normalmente representa Tipo, então +// culturalmente similar a como as pessoas usam i em um loop for +// para representar índice. T normalmente representa Tipo (Type), então // usaremos o nome completo para maior clareza // Nossa função usará inferência para sempre manter o tipo @@ -27,7 +27,7 @@ const stringArray = envolverEmArray("hello generics"); const numberArray = envolverEmArray(123); // Podemos verificar que isso funciona como esperado ao checar -// se podemos atribuir um array de strings à uma função que +// se podemos atribuir um array de strings a uma função que // deveria ser um array de objetos const naoArrayDeStrings: string[] = envolverEmArray({}); @@ -44,7 +44,7 @@ interface Desenhavel { desenhar: () => void; } -// Esta função receve um conjunto de objetos os quais possuem uma função +// Esta função recebe um conjunto de objetos que possuem uma função // para desenhar na tela function renderizarNaTela(entrada: Tipo[]) { entrada.forEach(i => i.desenhar()); @@ -80,7 +80,7 @@ interface HostDeCacheGenerico { } // Agora quando o HostDeCacheGenerico é usado, você deve dizer -// à dele qual é o TipoDeConteudo +// a dele qual é o TipoDeConteudo function adicionarObjetoTipadoAoCache>(obj: Tipo, cache: Cache): Cache { cache.salvar(obj); @@ -88,9 +88,9 @@ function adicionarObjetoTipadoAoCache Date: Fri, 18 Sep 2020 20:10:15 -0400 Subject: [PATCH 6/7] Clarify sentence --- .../JavaScript/Functions with JavaScript/Generic Functions.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts index b9bc21fb1b8b..776631b2843f 100644 --- a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts +++ b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts @@ -1,5 +1,5 @@ -// Tipos genéricos provêm uma forma de usar Tipos como variáveis em outros -// tipos. Meta. +// Tipos genéricos permitem usar Tipos como variáveis em outros tipos. +// Meta // Tentaremos manter este exemplo leve. Você pode fazer // muita coisa com tipos genéricos e é provável que veja algum código bem From 3bd1257baca66b23fb44350d8bf4b95845ab7591 Mon Sep 17 00:00:00 2001 From: Guilherme Varandas Date: Fri, 18 Sep 2020 20:11:43 -0400 Subject: [PATCH 7/7] Clarify sentence --- .../JavaScript/Functions with JavaScript/Generic Functions.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts index 776631b2843f..c635aaf2b37b 100644 --- a/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts +++ b/packages/playground-examples/copy/pt/JavaScript/Functions with JavaScript/Generic Functions.ts @@ -7,8 +7,8 @@ // não significa que tipos genéricos são complicados. // Vamos começar com um exemplo onde envolveremos um objeto de entrada -// em um array. Apenas nos importaremos com uma só variável neste -// caso: o tipo que foi passado como argumento: +// em um array. Só vamos nos importar com uma variável neste caso: +// o tipo que foi passado como argumento: function envolverEmArray(entrada: Tipo): Tipo[] { return [entrada];