Implementing a really simple Elvis Operator in TypeScript
Here is a simple routine that implements what is known as the Elvis Operator in TypeScript.
In C# you can write code like this
Nullable<int> age = person?.BestFriend?.Mother?.CurrentHusband?.Age);
If any of the values along the way it will return a null rather than throwing a NullReferenceException.
Using the class in my previous blog Get a Lambda expression as a string it is possible to achieve the same in TypeScript using the following format
const age = elvisOperator(person, x => x.bestFriend.mother.currentHusband.age;
It doesn't currently support anything more than simple property access, so you can't access elements in an array for example.
In C# you can write code like this
Nullable<int> age = person?.BestFriend?.Mother?.CurrentHusband?.Age);
If any of the values along the way it will return a null rather than throwing a NullReferenceException.
Using the class in my previous blog Get a Lambda expression as a string it is possible to achieve the same in TypeScript using the following format
const age = elvisOperator(person, x => x.bestFriend.mother.currentHusband.age;
It doesn't currently support anything more than simple property access, so you can't access elements in an array for example.
import { Expression } from './expression'; export function isUndefinedOrNull(value: any): boolean { return _.isNull(value) || _.isUndefined(value); } export function elvisOperator(instance: TSource, member: (v: TSource) => TResult): any { let path = Expression.pathAsArray(member); let result = instance; do { if (!isUndefinedOrNull(result) && path.length > 0) { result = result[path[0]]; path = path.slice(1); } } while (path.length > 0 && !isUndefinedOrNull(result)); return result; }
Comments