0

I want to add a ternary operator to add a class:

className={clsx(classes.text, {
   classes.textSmall]: children.length > 11,
})}

This works but I get a TypeScript error:

Object is possibly 'null' or 'undefined'. TS2533

I'm not sure what can be improved here. Would anyone be able to point me in the right direction?

1
  • Which object is possibly null or undefined? Is it classes or children? Commented Jul 31, 2020 at 3:46

1 Answer 1

2

If you are on Typescript version 3.7 you can use nullish coalescing and optional property access to deal with possibly null values within a ternary:

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

I'm assuming here that children is the possibly null value, here are some examples:

// Optional property access, double bang operator because it will resolve to undefined if the property is undefined
foo: !!(children?.length > 11);

// With nullish coalescing
bar: children?.length ?? 0 > 11;

// Without either
baz: children && children.length > 11;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.