Wat is het equivalent van een null-coalescentie-operator (??) in hoek 2?
In C# kunnen we deze bewerking uitvoeren:
string str = name ?? FirstName ?? "First Name is null";
Antwoord 1, autoriteit 100%
Coalescing wordt uitgevoerd via de operator ||
, d.w.z.
let str:string = name || FirstName || "name is null and FirstName is null";
Je kunt ook dezevraag lezen voor meer details en uitleg.
Antwoord 2, autoriteit 4%
In typoscript
Typescript heeft null-coalescentie geïntroduceerd met versie 3.7
, dus als je 3.7
of hoger gebruikt, kun je gewoon schrijven:
const str = name ?? firstName ?? "Name and First Name are both null";
const x = foo?.bar.baz() ?? bizz();
Zie https:// www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing.
In de hoekige sjabloon
Sinds Angular 12 kunt u ook ??
gebruiken in de sjabloon.
Antwoord 3
Misschien is dit wat je wilt bereiken:
let str =
typeof (name) !== 'undefined' && name !== null ?
name : typeof (FirstName ) === 'undefined' || FirstName === null ?
"First Name is null" : FirstName
Antwoord 4
De operator is toegevoegd in TypeScript 3.7
https://www.typescriptlang. org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing