Parçacıklara Dön
TypeScriptTypeScript

TypeScript Tip Korumaları

Güvenli tip kontrolü için çalışma zamanı tip daraltma fonksiyonları.

typescripttype guardnarrowingruntime
class=class="text-emerald-400">"text-gray">// User-defined type guard
interface Dog { kind: class=class="text-emerald-400">"text-emerald-400">'dog'; bark(): void }
interface Cat { kind: class=class="text-emerald-400">"text-emerald-400">'cat'; meow(): void }
type Animal = Dog | Cat

function isDog(animal: Animal): animal is Dog {
  return animal.kind === class=class="text-emerald-400">"text-emerald-400">'dog'
}

class=class="text-emerald-400">"text-gray">// Discriminated union guard
type ApiResponse<T> =
  | { status: class=class="text-emerald-400">"text-emerald-400">'success'; data: T }
  | { status: class=class="text-emerald-400">"text-emerald-400">'error'; error: string }

function isSuccess<T>(res: ApiResponse<T>): res is { status: class=class="text-emerald-400">"text-emerald-400">'success'; data: T } {
  return res.status === class=class="text-emerald-400">"text-emerald-400">'success'
}

class=class="text-emerald-400">"text-gray">// Null assertion guard
function assertDefined<T>(value: T | null | undefined, name: string): asserts value is T {
  if (value === null || value === undefined) {
    throw new Error(class="text-emerald-400">`Expected ${name} to be defined`)
  }
}

class=class="text-emerald-400">"text-gray">// Usage
const response: ApiResponse<string> = { status: class=class="text-emerald-400">"text-emerald-400">'success', data: class=class="text-emerald-400">"text-emerald-400">'hello' }
if (isSuccess(response)) {
  console.log(response.data) class=class="text-emerald-400">"text-gray">// TypeScript knows data exists
}

Nasıl Kullanılır

Union tipleri çalışma zamanında daraltmak için tip korumalarını kullanın. isDog(animal) tipi daraltır böylece TypeScript bark() çağırabilmenizi bilir. assertDefined bir değer null ise hata fırlatır ve TypeScript'in çağrıdan sonra tanımlı olarak ele almasını sağlar.

İlgili Teknoloji

TypeScript

Aklınızda Bir Proje mi Var?

Fikrinizi birlikte hayata geçirelim. 50+ teslim edilmiş projeyle sizi konseptten yayına hazır bir ürüne taşıyor; sabit fiyatlı tekliflerle özel yazılım geliştirme sunuyoruz. Hiçbir taahhüt olmadan ücretsiz danışmanlık alın.

veya ücretsiz görüşme ayarlayın