Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PT-BR] By Example.md and Do's and Dont's.md #72

Merged

Conversation

Perkles
Copy link
Contributor

@Perkles Perkles commented May 1, 2021

This PR translates the following documentation to Brazilian Portuguese.

  • Example.md
  • Do's and Dont's.md

📝 Notes:

I have translated Do's and Dont's to Sempre e Nunca. I know that it may look weird, but reads more natural in Portuguese.
Some exemples:

Don't ever use the types Number, String, Boolean, Symbol, or Object

to

Nunca use os tipos Number, String, Boolean, Symbol, ou Object

Ref: #1

@github-actions
Copy link
Contributor

github-actions bot commented May 1, 2021

Thanks for the PR!

This section of the codebase is owned by @khaosdoctor and @danilofuchs - if they write a comment saying "LGTM" then it will be merged.

@github-actions
Copy link
Contributor

github-actions bot commented May 1, 2021

Translation of By Example.md

title: Declaration Reference
layout: docs
permalink: /pt/docs/handbook/declaration-files/by-example.html

oneline: "How to create a d.ts file for a module"

The purpose of this guide is to teach you how to write a high-quality definition file.
The structure of this guide displays documentation for an API, along with usage samples and explanations of how to write the corresponding claim.

These examples are ordered in an approximate ascending order of complexity.

Objects with Properties

documentation

The global variable minhaLib has a function criaCumprimento to create greetings,
and a property numeroDeCumprimentos indicating the number of compliments made there.

code

let resultado = minhaLib.criaCumprimento("Olá, mundo");
console.log("O cumprimento computado é:" + resultado);

let count = minhaLib.numeroDeCumprimentos;

statement

Use declare namespace to describe types or values accessed via peer notation.

declare namespace minhaLib {
  function criaCumprimento(s: string): string;
  let numeroDeCumprimentos: number;
}

Overloaded Functions

documentation

The function pegaFerramenta accepts a number and returns a Tool, or accepts a string and returns an array of Tools.

code

let x: Ferramenta = pegaFerramenta(43);

let arr: Ferramenta[] = pegaFerramenta("todas");

statement

declare function pegaFerramenta(n: number): Ferramenta;
declare function pegaFerramenta(s: string): Ferramenta[];

Reusable Types (Interfaces)

documentation

When specifying a greeting, you must pass an object ConfiguracoesCumprimento.
This object has the following properties:

1 - greeting: String required

2 - duration: Optional length of time (in milliseconds)

3 - color: Optional string, e.g. '#ff00ff'

code

cumprimenta({
  cumprimento: "olá mundo",
  duracao: 4000
});

statement

Use a interface to define a type with properties.

interface ConfiguracoesCumprimento {
  cumprimento: string;
  duracao?: number;
  cor?: string;
}

declare function cumprimenta(setting: ConfiguracoesSaudacao): void;

Reusable types (Aliasetype)

documentation

Anywhere a greeting is expected, you can provide a string, a function returning a string, or an instantiation of Cumprimentador.

code

function pegaCumprimento() {
  return "oopa";
}
class MeuCumprimentador extends Cumprimentador {}

cumprimenta("olá");
cumprimenta(pegaCumprimento);
cumprimenta(new MeuCumprimentador());

statement

You can use an alias to make an abbreviation for a type:

type ComoUmCumprimentador = string | (() => string) | MeuCumprimentador;

declare function cumprimenta(g: ComoUmCumprimentador): void;

Organizing Types

documentation

The object cumprimentador can log to a file or show an alert.
You can provide LogOptions for .log(...) and alert options for .alert(...)

code

const g = new Cumprimentador("Olá");
g.log({ verbose: true });
g.alert({ modal: false, title: "Cumprimento Atual" });

statement

Use namespaces to organize types.

declare namespace CumprimentoLib {
  interface LogOptions {
    verbose?: boolean;
  }
  interface AlertOptions {
    modal: boolean;
    title?: string;
    color?: string;
  }
}

You can also create nested namespaces in a declaration:

declare namespace CumprimentoLib.Options {
  // Faz referência via CumprimentoLib.Options.Log
  interface Log {
    verbose?: boolean;
  }
  interface Alert {
    modal: boolean;
    title?: string;
    color?: string;
  }
}

Classes

documentation

You can create a greeter by instantiating the object Cumprimentador, or when creating a customized greeter when extending it.

code

const MeuCumprimentador = new Cumprimentador("Olá, mundo");
MeuCumprimentador.cumprimento = "oopa";
MeuCumprimentador.mostraCumprimento();

class CumprimentadorEspecial extends Cumprimentador {
  constructor() {
    super("Cumprimentador muito especial");
  }
}

statement

Use declare class to describe a class or object similar to the class.
Classes can also have properties and methods as well as a constructor.

declare class Cumprimentador {
  constructor(cumprimento: string);

  cumprimento: string;
  mostraCumprimento(): void;
}

Global Variables

documentation

The global variable foo contains the current number of tools.

code

console.log("Metade do numero de ferramentas é " + foo / 2);

statement

Use declare var to declare variables.
If the variable is read-only, you can use declare const.
You can also use declare let whether the variable is scope-closed.

/** O numero de ferramentas atual */
declare var foo: number;

Global Functions

documentation

You can call the function cumprimenta with a string to show a greeting to the user.

code

cumprimenta("olá, mundo");

statement

Use declare function to declare functions.

declare function cumprimenta(cumprimento: string): void;
Translation of Do's and Don'ts.md

title: Do's and Don'ts
layout: docs
permalink: /pt/docs/handbook/declaration-files/do-s-and-don-ts.html

oneline: "Recommendations for writing d.ts files"

General Types

Number, String, Boolean, Symbol And Object

never use the types Number, String, Boolean, Symbolor Object
These types reference non-primitive objects that are almost never used appropriately in JavaScript code.

/* Errado */
function reverte(s: String): String;

always use the types number, string, booleanand symbol.

/* OK */
function reverte(s: string): string;

Instead of Object, use the non-primitive type object (added in TypeScript 2.2).

Generics

never have a generic type that does not use the types of its parameters.
See more details at TypeScript FAQ page.

Any any

never Use any as type unless you are in the process of migrating the javascript project to Typescript. The compiler effectively Comes any like "please turn off the type check for this thing". This is similar to putting a comment @ts-ignore around each use of the variable. This can be very useful when you are first migrating a JavaScript project to TypeScript because you can set the type for things you haven't migrated as any, but in a full TypeScript project you will be disabling type checking for any part of your program that uses it.

In cases where you don't know the type you want to accept, or when you want to accept anything because it will go on blindly without interacting, you can use unknown.

Callback Types

Return Types and Callbacks

never use the return type any for callbacks whose value will be ignored:

/* ERRADO */
function fn(x: () => any) {
  x();
}

always use the return type void for callbacks whose value will be ignored:

/* OK */
function fn(x: () => void) {
  x();
}

Why is that?: Using void is safer because it prevents you from accidentally using the return value of x in an unverified manner:

function fn(x: () => void) {
  var k = x(); // oops! deveria fazer outra coisa
  k.facaAlgo(); // erro, mas ficaria OK se o tipo retorno tivesse sido 'any'
}

Optional Parameters in Callbacks

never use optional parameters on callbacks unless you actually have this intent:

/* ERRADO */
interface Buscador {
  retornaObjeto(pronto: (data: any, tempoDecorrido?: number) => void): void;
}

This has a very specific meaning: the callback pronto can be invoked with 1 argument or can be invoked with 2 arguments.
The author probably intended to say that the callback might not care about the parameter tempoDecorrido, but you don't need to do the optional parameter to achieve this --
it is always valid to provide a callback that accepts a smaller number of arguments.

always write callback parameters as non-optional:

/* OK */
interface Buscador {
  retornaObjeto(pronto: (data: any, tempoDecorrido: number) => void): void;
}

Overloads and Callbacks

never write separate overloads that differ only in the arity of the callback:

/* ERRADO */
declare function antesDeTodos(acao: () => void, timeout?: number): void;
declare function antesDeTodos(
  acao: (done: DoneFn) => void,
  timeout?: number
): void;

always write a single overload using the maximum arity:

/* OK */
declare function antesDeTodos(
  acao: (done: DoneFn) => void,
  timeout?: number
): void;

Why is that?: It is always valid for a callback to disregard a parameter, so there is no need to shorten the overhead.
Providing a shorter callback first allows incorrectly typed functions to be passed forward because they match the first overload.

Function Overloads

ordination

never put mental overloads before the most specific:

/* ERRADO */
declare function fn(x: any): any;
declare function fn(x: HTMLElement): number;
declare function fn(x: HTMLDivElement): string;

var meuElem: HTMLDivElement;
var x = fn(meuElem); // x: any, quê?

always order overloads by placing the most generic signatures after the most specific ones:

/* OK */
declare function fn(x: HTMLDivElement): string;
declare function fn(x: HTMLElement): number;
declare function fn(x: any): any;

var meuElem: HTMLDivElement;
var x = fn(meuElem); // x: string, :)

Why is that?: TypeScript chooses the first overload with matching when resolving calls to functions.
When a newer overload "is more general" than an older one, the oldest one is effectively omitted and cannot be called.

Use Optional Parameters

never write many overloads that differ only in the final parameters:

/* ERRADO */
interface Exemplo {
  diff(um: string): number;
  diff(um: string, dois: string): number;
  diff(um: string, dois: string, tres: boolean): number;
}

always optional parameters:

/* OK */
interface Exemplo {
  diff(um: string, dois?: string, tres?: boolean): number;
}

Note that this collapse should occur only when all overloads have the same return type.

Why is that?: This is important for two reasons.

TypeScript resolves signature compatibility by verifying that any target signatures can be called with the source arguments,and strange arguments are allowed.
This code, for example, exposes a bug only when the signature is written correctly using optional parameters:

function fn(x: (a: string, b: number, c: number) => void) {}
var x: Exemplo;
// Quando escrito com sobrecarga, OK -- usado a primeira sobrecarga
// Quando escrito com opcionais, devidamente um erro
fn(x.diff);

The second reason is when a consumer uses TypeScript's "strict null checking" functionality.
Because unspecified parameters appear as undefined in javascript, it's usually good to spend a undefined for a function with optional arguments.
This code, for example, should be OK under strict nulls:

var x: Exemplo;
// Quando escrito com sobrecargas,  um erro porque passa 'undefined' para 'string'
// Quando escrito com opcionais, devidamente OK
x.diff("algo", true ? undefined : "hora");

Use Union Types

never write overloads that differ by type in just one argument:

/* ERRADO */
interface Momento {
  utcOffset(): number;
  utcOffset(b: number): Momento;
  utcOffset(b: string): Momento;
}

always possible to use union types:

/* OK */
interface Momento {
  utcOffset(): number;
  utcOffset(b: number | string): Momento;
}

Realize we didn't b optional here because the return types of signatures are different.
Why is that?: This is important for people who are "passing on" a value for their role:

function fn(x: string): void;
function fn(x: number): void;
function fn(x: number | string) {
  // Quando escrito com sobrecargas separadas, indevidamente um erro
  // Quando escrito com tipos de união, 
  // When written with union types, devidamente OK
  return momento().utcOffset(x);
}

Generated by 🚫 dangerJS against a8cbd45

@khaosdoctor
Copy link
Contributor

I haven't forgotten this one, I'll review it shortly, sorry. I had some health issues

@khaosdoctor
Copy link
Contributor

LGTM

@github-actions
Copy link
Contributor

github-actions bot commented Aug 2, 2021

There was an issue merging, maybe try again khaosdoctor.

@khaosdoctor
Copy link
Contributor

LGTM

@github-actions
Copy link
Contributor

github-actions bot commented Aug 2, 2021

There was an issue merging, maybe try again khaosdoctor.

@khaosdoctor
Copy link
Contributor

@orta I think something is wrong with the bot

@orta
Copy link
Contributor

orta commented Aug 2, 2021

bad bot

@orta orta merged commit 00e1fee into microsoft:main Aug 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants