Learn TypeScript Help

Using Functions

Redefinindo funções

No TS se queremos redefinir uma função algo como polimorfismo, onde temos o mesmo nome da função mas a sua assinatura é diferente. Ou seja, o número de parametros é diferente podemos simplesmente deixar o mesmo nome da função e mudarmos a quantidade de parametros:

function calculateTax(amount) { return amount * 1.2; } function calculateTax(amount, discount) { return calculateTax(amount) - discount; } let taxValue = calculateTax(100); console.log(`Total Amount: ${taxValue}`);

O que disso que temos é que temos uma mesma função podendo ser executada de formas diferentes com base na

Using function parameters

function calculateTax(amount, discount) { return (amount * 1.2) - discount; } let taxValue = calculateTax(100, 0); console.log(`2 args: ${taxValue}`); taxValue = calculateTax(100); console.log(`1 arg: ${taxValue}`); taxValue = calculateTax(100, 10, 20); console.log(`3 args: ${taxValue}`)

Optional parameters

Para termos parametros opcionais usamos o simbolo de interrogação (?):

Assim podemos criar um fallback caso ele não exista:

function calculateTax(amount, discount?) { return (amount * 1.2) - (discount || 0); } let taxValue = calculateTax(100, 0); console.log(`2 args: ${taxValue}`); taxValue = calculateTax(100); console.log(`1 arg: ${taxValue}`); //taxValue = calculateTax(100, 10, 20); //console.log(`3 args: ${taxValue}`)

Using parameter with a default value

Podemos definir valores default (padrão) para parametros assim temos um fallback já no código caso não seja passado

function calculateTax(amount, discount = 0) { return (amount * 1.2) - discount; } let taxValue = calculateTax(100, 0); console.log(`2 args: ${taxValue}`); taxValue = calculateTax(100); console.log(`1 arg: ${taxValue}`); //taxValue = calculateTax(100, 10, 20); //console.log(`3 args: ${taxValue}`);

Assim temos que valores default tornam esse parametro optional, já que se não for definido ele usara o fallback

Using a rest parameter

A contra partida de parametros opcionais é o rest parameters, que permite uma função aceitar um número variavel de argumentos extras que são agrupados juntos e apresentados juntos

Uma função pode ter somente um rest parameter

function calculateTax(amount, discount = 0, ...extraFees) { return (amount * 1.2) - discount + extraFees.reduce((total, val) => total + val, 0); } let taxValue = calculateTax(100, 0); console.log(`2 args: ${taxValue}`); taxValue = calculateTax(100); console.log(`1 arg: ${taxValue}`); taxValue = calculateTax(100, 10, 20); console.log(`3 args: ${taxValue}`)

O rest parameters é criado com o três pontos (ellipsis) ... antes do nome do parametro:

  • Os parametros seguem a ordem deles conforme a ordem

  • Qualquer argumento adicional que não tenha parametro correspondente vai para o rest parameter

  • O parametro sempre será um array

    • Senão tiver argumentos extras, será passado um array vazio []

    • Se houver, conterá todos os valores adicionais

Applying type annotations to function parameters

Por padrão o compiler define o type dos parameters como null, mas podemos deixar tudo mais específico

Para isso basta fazermos o normal e definirmos um type com dois pontos e o type na frente do nome dop parametro:

Para um parametro defaul o type annotation vem antes:

E para um rest parameter, costuma ser apenas um array de algum type:

function calculateTax(amount: number, discount: number = 0, ...extraFees: number[]) { return (amount * 1.2) - discount + extraFees.reduce((total, val) => total + val, 0); } let taxValue = calculateTax(100, 0); console.log(`2 args: ${taxValue}`); taxValue = calculateTax(100); console.log(`1 arg: ${taxValue}`); taxValue = calculateTax(100, 10, 20) console.log(`3 args: ${taxValue}`); taxValue = calculateTax(100, 10, 20, 1, 30, 7); console.log(`6 args: ${taxValue}`)

Controlling null parameters values

Para controlar para que não usar valores null ou undefined

function calculateTax(amount: number, discount: number = 0, ...extraFees: number[]) { return (amount * 1.2) - discount + extraFees.reduce((total, val) => total + val, 0); } let taxValue = calculateTax(null, 0); console.log(`Tax value: ${taxValue}`);

Understanding Function Results

O compilador do TS para os retornos tenta inferir o tipo automaticamente, com base no código

  • Se uma função retornar mais de um valor o compilador irá usar o type union para os tipos inferidos

Disabling implicit returns

Para desabilitarmos o retorno implicito e assim forçar para que todo retorno tenha seu type declarado devemos adicionar uma compiler option que vai fazer com que tenhamos isso:

  • tsconfig.json

{ "compilerOptions": { "target": "es2018", "outDir": "./dist", "rootDir": "./src", "declaration": true, "strictNullChecks": true, "noImplicitReturns": true } }

Using typer annotations for function results

Isso funciona para explicitarmos o tipo de retorno:

function calculateTax(amount: number, discount: number = 0, ...extraFees: number[]): number { return (amount * 1.2) - discount + extraFees.reduce((total, val) => total + val, 0); } let taxValue = calculateTax(100, 0); console.log(`Tax value: ${taxValue}`)

Defining void functions

Funções que não retornam nada são procedimentos e procedimentos tem o seu tipo como void

function calculateTax(amount: number, discount: number = 0, ...extraFees: number[]): number { return (amount * 1.2) - discount + extraFees.reduce((total, val) => total + val, 0); } function writeValue(label: string, value: number): void { console.log(`${label}: ${value}`); } writeValue("Tax value", calculateTax(100, 0))

Overloading Function Types

O type union pode fazer iso possivel para definir um range de types para parametros de funções e retornos, mas eles não permitem o relacionamento entre eles para ser expressado de forma certa:

function calculateTax(amount: number | null): number | null { if (amount != null) { return amount * 1.2; } return null; } function writeValue(label: string, value: number): void { console.log(`${label}: ${value}`); } let taxAmount: number | null = calculateTax(100); if (typeof taxAmount === "number") { writeValue("Tax value", taxAmount); }

Assim podemos fazer a sobrecarga de tipos com o TS, basta definir a função e tipar o que queremos:

function calculateTax(amount: number): number; function calculateTax(amount: null): null; function calculateTax(amount: number | null): number | null { if (amount != null) { return amount * 1.2; } return null; }
function calculateTax(amount: number): number; function calculateTax(amount: null): null; function calculateTax(amount: number | null): number | null { if (amount != null) { return amount * 1.2; } return null; } function writeValue(label: string, value: number): void { console.log(`${label}: ${value}`); } let taxAmount: number = calculateTax(100); //if (typeof taxAmount === "number") { writeValue("Tax value", taxAmount); //}
13 November 2025