VScode API 为什么我获取不到当前行?
VScode API why can't I get the current line?
我正在使用打字稿编写 vs 代码扩展,但由于某种原因我无法获取当前行。
我要实现的功能是:
function makeFrame()
{
vscode.window.activeTextEditor.selection.active.line;
}
失败并出现错误:对象可能未定义
导入语句是:
import {window, commands, Disposable, ExtensionContext, StatusBarAlignment, StatusBarItem, TextDocument} from 'vscode';
我做错了什么?
(我是 TypeScript 的新手,也是 VS 代码的新手)
activeTextEditor
可能是 undefined
。这表明没有活动的编辑器,例如当您第一次打开一个新工作区或关闭所有编辑器时会发生这种情况
要修复,只需添加一个快速检查:
function makeFrame()
{
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor) {
activeEditor.selection.active.line;
}
}
Object is possibly undefined
因为可能有也可能没有 activeEditor
。
您可以进行显式检查:
function makeFrame() {
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor != null) {
activeEditor.selection.active.line;
}
}
或者 assertion 如果您确定:
function makeFrame()
{
vscode.window.activeTextEditor!.selection.active.line;
}
我正在使用打字稿编写 vs 代码扩展,但由于某种原因我无法获取当前行。
我要实现的功能是:
function makeFrame()
{
vscode.window.activeTextEditor.selection.active.line;
}
失败并出现错误:对象可能未定义 导入语句是:
import {window, commands, Disposable, ExtensionContext, StatusBarAlignment, StatusBarItem, TextDocument} from 'vscode';
我做错了什么?
(我是 TypeScript 的新手,也是 VS 代码的新手)
activeTextEditor
可能是 undefined
。这表明没有活动的编辑器,例如当您第一次打开一个新工作区或关闭所有编辑器时会发生这种情况
要修复,只需添加一个快速检查:
function makeFrame()
{
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor) {
activeEditor.selection.active.line;
}
}
Object is possibly undefined
因为可能有也可能没有 activeEditor
。
您可以进行显式检查:
function makeFrame() {
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor != null) {
activeEditor.selection.active.line;
}
}
或者 assertion 如果您确定:
function makeFrame()
{
vscode.window.activeTextEditor!.selection.active.line;
}