Pular para o conteúdo principal
ProdutosFerramentas de desktopTASTECADVisualização de desenhosTASTEFILESGerenciamento de arquivosTASTEFTPTransferência de arquivosTASTESSHEspaço de trabalho remotoTASTEZIPCompactação e extraçãoTASTEWINMGerenciamento de arquivosFerramentas para desenvolvedoresTASTECODEAmbiente de desenvolvimento integrado para RustTASTESTUDIOAmbiente integrado de desenvolvimento e testesTASTEETLIntegração de dados (ETL)ServidoresTASTEREMOTEServidor de área de trabalho remotaTASTEGEOServidor geoespacialTASTEMAILEspaço de trabalho de e-mailInvestimentosTASTESTOCKAplicativo desktop de negociação automática de açõesComeçarDownloadsDocumentaçãoComprarTodos os produtos
Marketplace
Notícias
TecnologiaNotíciasNotícias de desenvolvimento de hojeDocumentaçãoLinguagens de programaçãoRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps e desktopTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos essenciaisAlgoritmos avançadosAlgoritmos práticos
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrineGuia da comunidade
ColaboreTransferência técnicaConstrução de siteConstrução de app de desktopPipeline de lançamento e pagamentoParceiro de vendasContato
ServiçosÁrea de trabalho remotaPacotes de instalação sob medida
TASTEDEV
Produtos

Ferramentas de desktop

TASTECADDesenhos complexos, abertos com levezaTASTEFILESSó os arquivos de que você precisa, o mais rápido possívelTASTEFTPO caminho mais organizado para seus arquivosTASTESSHEntre você e o servidor, uma conexão mais sólidaTASTEZIPCompacte mais rápido, extraia com mais segurançaTASTEWINMUm gerenciador de arquivos de dois painéis feito para o teclado

Ferramentas para desenvolvedores

TASTECODEEdite, compile, depure e teste apps Rust em uma única janelaTASTESTUDIODa edição aos testes remotos e às correções com IA aprovadasTASTEETLMova dados de olho nos valores

Servidores

TASTEREMOTEUma área de trabalho remota rodando no seu próprio servidorTASTEGEOUm servidor geoespacial compatível com o GeoServer, reconstruído em RustTASTEMAILRetome o controle do seu e-mail

Investimentos

TASTESTOCKNegociação automática de ações pelas regras que você define: quando e o quê

Começar

DownloadsVersões mais recentes de cada produtoDocsComo usar cada produtoComprarAssinaturas e licenças perpétuasTodos os produtosTodos os produtos de relance
Todos os produtos
MarketplaceNotícias
Tecnologia

Notícias

Notícias de desenvolvimento de hojeAnúncios oficiais de linguagens, frameworks, GitHub e IADocumentaçãoGuias de linguagens, frameworks e algoritmos

Linguagens de programação

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps e desktopTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálise de complexidade · Ordenação · Busca · Estruturas de dados básicas · Árvores e heapsAlgoritmos essenciaisBusca em grafos · Caminho mínimo e árvore geradora mínima · Programação dinâmica · Algoritmos gulosos · Divisão e conquista · BacktrackingAlgoritmos avançadosAlgoritmos de strings · Matemática e teoria dos números · Manipulação de bits · Árvores de segmentos · Union-FindAlgoritmos práticosEstratégia para entrevistas de código · Cache LRU · Limitação de taxa · Hashing consistente
Toda a documentação de desenvolvimento
Comunidade
ProjetosDescubra criadores e trabalhosRegistros de desenvolvimentoDecisões e aprendizadosPromptsInstruções reutilizáveisProblemas de ferramentas de IAProblemas e contornos de Claude, Codex, GeminiVitrineResultados concluídosGuia da comunidadeComo construímos em aberto
Colabore
Transferência técnicaApps nativos em Rust e eguiConstrução de site10 idiomas, contas, documentação e downloadsConstrução de app de desktopRust e egui, sem WebViewPipeline de lançamento e pagamentoAssinatura, MSI, deb, rpm, AppImage, hashesParceiro de vendasRecomende e ganhe 30%ContatoDesenvolvimento, parcerias e investimento
Serviços
Área de trabalho remotaAcesse seu computador pelo navegadorPacotes de instalação sob medidaSó o necessário, configurações pré-carregadas
Comprar
PT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Entrar
Entrar
TASTEDEV

De pequenas ferramentas a um desenvolvimento melhor.

support@tastedev.netApoiar TASTEDEV
ProdutosLinha de produtosComprarDocsDownloadsMarketplaceSuporte
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrine
PolíticasSobre nósPolítica de privacidadeTermos de usoTermos de assinaturaReembolsoDiretrizes da comunidade
ContaEntrarCriar conta
Visitantes
Hoje
Ontem
Visualizações totais
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro comercial
853-44-00368
Endereço
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsável pela privacidade
CHOI YOUNG GU

© 2026 TASTEDEVAs informações dos produtos se baseiam em fontes de desenvolvimento verificadas.Lançado · em melhoria

Documentação de TypeScript
TypeScript
Getting StartedSyntax BasicsTypes and DataModules and PackagesErrors and TestingKey Concepts: The Type System
Discussões

Guia de TypeScript · 6/6

Key Concepts: The Type System

Por enquanto, este capítulo está disponível apenas em inglês.

TypeScript's real power lives in its type system. This chapter digs into generics for reusable types, narrowing and type guards that follow your control flow, discriminated unions for modeling state safely, utility types for transforming existing types, and the strict mode settings that make all of it trustworthy.

Generics

Generics let a function or type take a type as a parameter, so it can work with many types without forgetting which one it was given. Constrain a type parameter with extends, and combine it with keyof to tie an object's keys to their value types.

function first<T>(items: T[]): T | undefined {
  return items[0];
}
const n = first([1, 2, 3]);       // number | undefined
const s = first(["a", "b"]);      // string | undefined

function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}
longest("hello", "hi");           // string
longest([1, 2], [1, 2, 3]);       // number[]

function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
const user = { name: "Kim", age: 30 };
const age = getProp(user, "age"); // number
// getProp(user, "email");        // error: not a key of user

interface ApiResponse<T> {
  data: T;
  status: number;
}

With any you could accept anything, but the return type would be lost. Generics keep both flexibility and safety.

Narrowing and type guards

A value with a union type gets refined to something more specific as it passes through checks. The compiler understands typeof, instanceof, the in operator, equality comparisons, and truthiness checks. To turn your own checking function into a type guard, give it a type predicate of the form value is Type as its return type.

interface Cat { meow(): void }
interface Dog { bark(): void }

function speak(pet: Cat | Dog) {
  if ("meow" in pet) pet.meow();  // Cat
  else pet.bark();                // Dog
}

function isString(value: unknown): value is string {
  return typeof value === "string";
}

function shout(input: unknown) {
  if (isString(input)) {
    console.log(input.toUpperCase()); // narrowed to string
  }
}

function len(text: string | null): number {
  if (!text) return 0;            // filters out null and ""
  return text.length;             // string
}

Discriminated unions

A discriminated union is a union whose members share a property, usually called kind or type, holding a different literal value in each member. Switch on that property and every branch knows the exact member it is dealing with. Assigning to never in the default branch turns forgotten cases into compile errors when the union grows.

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number }
  | { kind: "rect"; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle": return Math.PI * shape.radius ** 2;
    case "square": return shape.size ** 2;
    case "rect":   return shape.width * shape.height;
    default: {
      const unreachable: never = shape; // errors if a case is missing
      return unreachable;
    }
  }
}
Dúvidas sobre este capítulo?
Capítulo anteriorErrors and Testing

This pattern shines for UI states such as loading, success, and failure, and for message types exchanged with a server.

Utility types

TypeScript ships a set of built-in utility types that derive new types from existing ones.

UtilityEffect
Partial<T>Makes every property optional
Required<T>Makes every property required
Readonly<T>Makes every property read-only
Pick<T, K> and Omit<T, K>Keep or drop selected properties
Record<K, V>An object with keys K and values V
ReturnType<F> and Parameters<F>A function's return and parameter types
Awaited<T>The value a Promise resolves to
interface Todo {
  id: number;
  title: string;
  done: boolean;
}

type TodoPatch = Partial<Omit<Todo, "id">>;  // title?, done?
type TodoPreview = Pick<Todo, "id" | "title">;
type ByStatus = Record<"open" | "closed", Todo[]>;

function update(todo: Todo, patch: TodoPatch): Todo {
  return { ...todo, ...patch };
}

const config = {
  port: 3000,
  mode: "dev",
} satisfies Record<string, string | number>;

The satisfies operator at the end validates a value against a type while keeping the narrower inferred type, instead of widening the variable to the annotation.

Strict mode

"strict": true turns on a family of checks at once. The ones that matter most:

  • strictNullChecks treats null and undefined as distinct types, so you cannot use a possibly missing value without checking it.
  • noImplicitAny stops parameters and variables from silently falling back to any.
  • strictPropertyInitialization verifies that class properties are assigned in the constructor.
  • useUnknownInCatchVariables types catch variables as unknown.

Some useful checks live outside the strict family. noUncheckedIndexedAccess, for example, adds undefined to values read through array indexes or index signatures.

Summary

  • Generics build reusable functions and types without losing type information.
  • Narrowing refines unions through typeof, instanceof, in, and more; value is T creates custom guards.
  • Discriminated unions plus a never check guarantee every case is handled.
  • Utility types such as Partial, Pick, Omit, and Record reshape existing types.
  • Keep strict on, always.

Where to go next in the official documentation:

  • The TypeScript Handbook
  • Generics
  • Narrowing
  • Utility Types
  • TSConfig Reference
  • TypeScript Playground

0 comentários

Principais comentáriosMais recentes primeiro

Fazer login · Faça login para deixar um comentário.