TypeScript中如何简化对象字段是否为undefined的检查表达式?
问题描述
我需要检查textAreaRef.current和textAreaRef.current.resizableTextArea是否为undefined/null值。
以下写法可行:
if (textAreaRef.current && textAreaRef.current.resizableTextArea) { const currentCursorPosition = textAreaRef.current.resizableTextArea.textArea.selectionStart; }
但以下写法会触发TypeScript错误:
function isTextAreaExists() { return textAreaRef.current && textAreaRef.current.resizableTextArea; } if (isTextAreaExists()) { const currentCursorPosition = textAreaRef.current.resizableTextArea.textArea.selectionStart; }
错误信息
TS18047: textAreaRef.current is possibly null
TS18048: textAreaRef.current.resizableTextArea is possibly null
请问有没有简化这种检查表达式的方法?
解决方案
1. 提取嵌套属性+可选链(推荐)
通过可选链?.提前提取目标属性,让TypeScript自动推断非空状态,写法简洁且类型安全:
const resizableTextArea = textAreaRef.current?.resizableTextArea; if (resizableTextArea) { const currentCursorPosition = resizableTextArea.textArea.selectionStart; }
2. 给辅助函数添加类型谓词
如果必须用辅助函数,可通过自定义类型谓词明确告知TypeScript判断后的类型状态:
function isTextAreaExists(): textAreaRef.current is { resizableTextArea: NonNullable<typeof textAreaRef.current['resizableTextArea']> } { return !!textAreaRef.current && !!textAreaRef.current.resizableTextArea; } if (isTextAreaExists()) { const currentCursorPosition = textAreaRef.current.resizableTextArea.textArea.selectionStart; }
3. 非空断言(谨慎使用)
若能确保代码执行时目标属性一定存在,可直接用!跳过检查,但仅适用于确定非空的场景:
const currentCursorPosition = textAreaRef.current!.resizableTextArea!.textArea.selectionStart;
原写法报错原因
TypeScript的类型窄化仅在当前代码块内有效,辅助函数的返回值无法让TS跟踪外部变量textAreaRef.current的状态,因此仍会判定其可能为空。
内容的提问来源于stack exchange,提问作者Boi Stance
相关产品推荐
相关产品推荐

