How can I use optional chaining with arrays and functions? - javascript

I'm trying to use optional chaining with an array instead of an object but not sure how to do that:
Here's what I'm trying to do myArray.filter(x => x.testKey === myTestKey)?[0].
Also trying similar thing with a function:
let x = {a: () => {}, b: null}
console.log(x?b());
But it's giving a similar error - how can I use optional chaining with an array or a function?

You need to put a . after the ? to use optional chaining:
myArray.filter(x => x.testKey === myTestKey)?.[0]
Playground link
Using just the ? alone makes the compiler think you're trying to use the conditional operator (and then it throws an error since it doesn't see a : later)
Optional chaining isn't just a TypeScript thing - it is a finished proposal in plain JavaScript too.
It can be used with bracket notation like above, but it can also be used with dot notation property access:
const obj = {
prop2: {
nested2: 'val2'
}
};
console.log(
obj.prop1?.nested1,
obj.prop2?.nested2
);
And with function calls:
const obj = {
fn2: () => console.log('fn2 running')
};
obj.fn1?.();
obj.fn2?.();

Just found it after a little searching on the what's new page on official documentation
The right way to do it with array is to add . after ?
so it'll be like
myArray.filter(x => x.testKey === myTestKey)?.[0]
I'll like to throw some more light on what exactly happens with my above question case.
myArray.filter(x => x.testKey === myTestKey)?[0]
Transpiles to
const result = myArray.filter(x => x.testKey === myTestKey) ? [0] : ;
Due to which it throws the error since there's something missing after : and you probably don't want your code to be transpilled to this.
Thanks to Certain Performance's answer I learned new things about typescript especially the tool https://www.typescriptlang.org/play/index.html .

ECMA 262 (2020) which I am testing on Edge Chromium 84 can execute the Optional Chaining operator without TypeScript transpiler:
// All result are undefined
const a = {};
console.log(a?.b);
console.log(a?.["b-foo-1"]);
console.log(a?.b?.());
// Note that the following statements throw exceptions:
a?.(); // TypeError: a is not a function
a?.b(); // TypeError: a?.b is not a function
CanIUse: Chrome 80+, Firefox 74+

After a bit of searching the new page in the official documentation, it was discovered.
You need to put a . after the ? to use optional chaining.
So it will be so,
myArray.filter(x => x.testKey === myTestKey)?.[0]
Used only ? Makes the compiler think that you are trying to use a conditional operator (then it causes an error because it doesn't see a : later)

It's not necessary that the function is inside the object, you can run a function using optional chaining also like this:
someFunction?.();
If someFunction exists it will run, otherwise it will skip the execution and it will not error.
This technique actually is very useful especially if you work with reusable components and some components might not have this function.

Well, even though we figured out the correct syntax, the code doesn't make much sense to me.
The optional chaining in the code above is making sure, that the result of myArray.filter(x => x.testKey === myTestKey) is not null and not undefined (you can have a look at the TS output). But it is not possible anyway, because the result of the filter method is always an array. Since JavaScript doesn't throw "Array bounds exceeded", you are always safe when you try to access any index - you will get undefined if this element doesn't exist.
More example to make it clear:
const myArray: string[] = undefined
console.log(myArray.filter(x => x)?.[0]) //throws Cannot read property 'filter' of undefined
//in this example the optional chaining protects us from undefined array
const myArray: string[] = undefined
console.log(myArray?.filter(x => x)[0]) //outputs "undefined"

Related

What's the syntax to use Javascript optional chaining with a space in the property name? [duplicate]

TypeScript 3.7 now supports the optional chaining operator. Hence, you can write code such as:
const value = a?.b?.c;
I.e., you can use this operator to access properties of an object, where the object itself may be null or undefined. Now what I would like to do is basically the same, but the property names are dynamic:
const value = a?[b]?.c;
However, there I get a syntax error:
error TS1005: ':' expected.
What am I doing wrong here? Is this even possible?
The proposal seems to imply that this is not possible (but maybe I get the syntax examples wrong).
When accessing a property using bracket notation and optional chaining, you need to use a dot in addition to the brackets:
const value = a?.[b]?.c;
This is the syntax that was adopted by the TC39 proposal, because otherwise it's hard for the parser to figure out if this ? is part of a ternary expression or part of optional chaining.
The way I think about it: the symbol for optional chaining isn't ?, it's ?.. If you're doing optional chaining, you'll always be using both characters.
The Optional Chaining operator is ?.
Here are some examples for nullable property and function handling.
const example = {a: ["first", {b:3}, false]}
// Properties
example?.a // ["first", {b:3}, false]
example?.b // undefined
// Dynamic properties ?.[]
example?.a?.[0] // "first"
example?.a?.[1]?.a // undefined
example?.a?.[1]?.b // 3
// Functions ?.()
null?.() // undefined
validFunction?.() // result
(() => {return 1})?.() // 1
Bonus: Default values
?? (Nullish Coalescing) can be used to set a default value if undefined or null.
const notNull = possiblyNull ?? defaultValue
const alsoNotNull = a?.b?.c ?? possiblyNullFallback ?? defaultValue

How to test this statement using jest and enzyme

In our code, I have two statements
const { column, showTooltip, tooltipValue, data } = props;
const key = column.bindProperties[0].properties[0].name;
on testing, this gives error as
"TypeError: Cannot read property '0' of undefined."
what is the meaning of this statement column.bindProperties[0].properties[0].name; and how to test it.
In JS you can't guarantee that objects have certain properties.
When you try to access column.bindProperties[0].properties[0].name, either column.bindProperties or column.bindProperties[0].properties is undefined - hence the error you're getting.
You can either use lodash's _.get() or validate the keys are defined using the redundantly annoying:
const key = column
&& column.bindProperties
&& column.bindProperties[0]
&& column.bindProperties[0].properties
&& column.bindProperties[0].properties[0]
&& column.bindProperties[0].properties[0].name;
This will make sure your code won't break. If one expression in the chain isn't defined, the expression will stop evaluating and you'll just get undefined as the result.
Since no one has really just spelt it out, here's an example of optional chaining:
const key = column?.bindProperties?.[0]?.properties?.[0]?.name;
and with nullish coalescing:
const key = column?.bindProperties?.[0]?.properties?.[0]?.name ?? "I'm a fallback value";

TS2532: Object is possibly 'undefined'. on array.map()

I understand that this TS error is essentially just a warning but I have been unable to find a solution when it occurs on .map
const files = require.context("./", true, /\.vue$/i);
files.keys().map(key =>
Vue.component(
key
.split("/")
.pop()
.split(".")[0],
files(key).default
)
);
I have tried checking if the value of key exists before doing anything else but it still produces the same error.
TS2532: Object is possibly 'undefined'.
You are trying to split a string. Using someString.split("/"), which does return an array. Using the method pop() does either return the last element of the array or undefined (according to MDN)
Therefore your typing at that point is: string | undefined executing .split(..) on an undefined value will cause problems. That's what TypeScript is trying to tell you here.
To avoid this warning/error and to be type safe you could use the latest optional chaining feature TypeScript 3.7.0 provides you if applicable:
key.split("/").pop()?.split(".")[0] ?? someDefaultString
An alternative solution would be to extract this kind of logic into another function like so:
function extractValue(key: string): string { // you want to name that function better though
return key.split("/").pop()?.split(".")[0] ?? "defaultValue";
}
And use it like:
Vue.component(extractValue(key), files(key).default)

Using optional chaining operator for object property access

TypeScript 3.7 now supports the optional chaining operator. Hence, you can write code such as:
const value = a?.b?.c;
I.e., you can use this operator to access properties of an object, where the object itself may be null or undefined. Now what I would like to do is basically the same, but the property names are dynamic:
const value = a?[b]?.c;
However, there I get a syntax error:
error TS1005: ':' expected.
What am I doing wrong here? Is this even possible?
The proposal seems to imply that this is not possible (but maybe I get the syntax examples wrong).
When accessing a property using bracket notation and optional chaining, you need to use a dot in addition to the brackets:
const value = a?.[b]?.c;
This is the syntax that was adopted by the TC39 proposal, because otherwise it's hard for the parser to figure out if this ? is part of a ternary expression or part of optional chaining.
The way I think about it: the symbol for optional chaining isn't ?, it's ?.. If you're doing optional chaining, you'll always be using both characters.
The Optional Chaining operator is ?.
Here are some examples for nullable property and function handling.
const example = {a: ["first", {b:3}, false]}
// Properties
example?.a // ["first", {b:3}, false]
example?.b // undefined
// Dynamic properties ?.[]
example?.a?.[0] // "first"
example?.a?.[1]?.a // undefined
example?.a?.[1]?.b // 3
// Functions ?.()
null?.() // undefined
validFunction?.() // result
(() => {return 1})?.() // 1
Bonus: Default values
?? (Nullish Coalescing) can be used to set a default value if undefined or null.
const notNull = possiblyNull ?? defaultValue
const alsoNotNull = a?.b?.c ?? possiblyNullFallback ?? defaultValue

Check if sub-object exists before using it

In order to prevent using an object's value that doesn't exist (which would throw an error), I usually do something like this:
if(apple.details){
// do something with apple.details
}
and it normally works fine. But if it's about a "object's object's value", like apple.details.price, that doesn't work, because if not even .details exists, the if() would throw an error.
What can I do or is there generally a better way to do this?
You can do chain:
if (apple && apple.details && apple.details.price) { ... }
But it's not convenient if the chain is long. Instead you can use lodash.get method
With lodash:
if (get(apple, 'details.price')) { ... }
Since 2020:
The best way to solve this is using the Optional Chaining Operator
if(apple?.details) // Undefined if apple does not exist
Suggestion of lodash is no longer required when using runtime compatible with ES2020 i.e. Most browsers today & node>14.5
You may try solution of #Sphinx
I would also suggest _.get(apple, 'details.price') of lodash, but surely it is not worth to include whole library for simple project or few tasks.
_.get() function also prevents from throwing error, when even apple variable is not defined (undefined)
You would have to check each parent object prior to checking the nested child object, i.e., if (a && a.b && a.b.c) {}
If you're using LoDash, you can use the _.get function with an optional default:
let obj = {'a': {'b': {'c': 42} } };
let result = _.get(obj, 'a.b.c'); // 42
let result2 = _.get(obj, 'a.b.d'); // undefined
let result3 = _.get(obj, 'a.c.d', null); // null
If you're not using LoDash, you can implement a simplified version of _.get as shown in this answer.

Categories

Resources