29 Temmuz 2021 Perşembe

TypeScript Optional

Örnek
Şöyle yaparız
interface Cat {
  name: string;
  age: number;
  ownerName?: string; // not every cat has an owner
}

const mrWhitePaws: Cat = {
  name: "Mr. White Paws",
  age: 7,
  ownerName: "Jane", // domestic cat, lucky guy
};

const wildLynx: Cat = {
  name: "Lynx lynx",
  age: 6,
  // this wild cat lives a free life!
};
Örnek
null Guard yerine Optional kullanmak çok daha kolay. Şöyle yaparız.
element?.innerText = 'Hello';
optional chaining ve nullish coalescing
Açıklaması şöyle
The optional chaining allows to safely “navigate” through possibly absent values (without throwing an error), while the nullish coalescing operator, or the ??, enables providing a failover (default) value in case of stumbling upon a null (think of it as a good, old || operator, but for null or undefined values only, instead of all “falsy” ones). Again, keep in mind, that this is an example of a feature eventually available in pure JavaScript, too.
Örnek
Şöyle yaparız
// optional chaining:
// The value will be undefined. Without `?.`, this would error with
// "Uncaught TypeError: Cannot read property 'length' 
const nameLength: string | undefined = wildLynx?.name?.length; of undefined".

// nullish coalescing:
const nope = null;
const calculation = (nope ?? 0) + 42; // The value will be 0 + 42, ergo 42.

Hiç yorum yok:

Yorum Gönder