【问题标题】:How to solve TypeScript `possibly null` error within ternary?如何解决三元中的 TypeScript `possibly null` 错误?
【发布时间】:2020-07-31 03:35:48
【问题描述】:

我想添加一个三元运算符来添加一个类:

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

这可行,但我收到 TypeScript 错误:

对象可能是“空”或“未定义”。 TS2533

我不确定这里有什么可以改进的。有人能指出我正确的方向吗?

【问题讨论】:

  • 哪个对象可能是nullundefined?是classes 还是children

标签: reactjs typescript


【解决方案1】:

如果您使用的是 Typescript 3.7 版,则可以使用 nullish 合并和可选属性访问来处理三元组中可能为 null 的值:

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

我在这里假设 children 可能是 null 值,这里有一些例子:

// 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-05
    • 2019-07-10
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    相关资源
    最近更新 更多