Geri

TypeScript NonNullable Utility Type

`NonNullable< T >`, `T` tipinden `null` ve `undefined` türlerini çıkarır. Böylece sadece geçerli değerler kalır.

Temel Kullanım

type MaybeString = string | null | undefined;
  
  let value1: MaybeString = "hello";
  value1 = null;         // OK
  value1 = undefined;    // OK
  
  type NonNullString = NonNullable<MaybeString>;
  
  let value2: NonNullString = "world";
  // value2 = null;      // Error: Type 'null' is not assignable
  // value2 = undefined; // Error: Type 'undefined' is not assignable

`string | null | undefined` gibi tiplerden null ve undefined çıkarılarak daha güvenli tipler oluşturulur.

Fonksiyonlarda Kullanımı

function processValue(value: string | null | undefined) {
    if (value == null) {
      console.log("Value is null or undefined");
    } else {
      // After check, 'value' is string (non-nullable)
      const trimmed = value.trim();
      console.log(trimmed);
    }
  }
  
  function processNonNullValue(value: NonNullable<string | null | undefined>) {
    // No need to check for null or undefined here
    const trimmed = value.trim();
    console.log(trimmed);
  }

Fonksiyon parametrelerinde `NonNullable` kullanarak, null kontrolünü kaldırabilir ve doğrudan geçerli tiplerle çalışabilirsiniz.

Nesne Alanlarında Kullanımı

type OptionalUser = {
    name?: string | null;
    age?: number | null;
  };
  
  type RequiredUser = {
    [K in keyof OptionalUser]: NonNullable<OptionalUser[K]>;
  };
  
  const user1: OptionalUser = { name: null, age: 25 };
  // const user2: RequiredUser = { name: null, age: 25 }; // Error: name cannot be null

Optional veya nullable alanlar `NonNullable` ile zorunlu ve null olmayan alanlara çevrilebilir.

Neden Kullanılır?

`NonNullable`, tip güvenliğini artırır, gereksiz null ve undefined kontrollerini azaltır, böylece daha temiz ve hatasız kod yazılır.

Geri