繁体   English   中英

VScode API为什么我不能获得当前行?

[英]VScode API why can't I get the current line?

我正在使用typescript来编写vs代码扩展,由于某种原因我无法获得当前行。

我想要做的功能是:

function makeFrame()
{
    vscode.window.activeTextEditor.selection.active.line;
}

哪个失败并出现错误:对象可能未定义import语句为:

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

对象可能未定义

因为可能有也可能没有activeEditor

你可以做一个明确的检查:

function makeFrame() {
    const activeEditor = vscode.window.activeTextEditor;
    if (activeEditor != null) {
        activeEditor.selection.active.line;
    }
}

如果您确定,可以断言

function makeFrame()
{
    vscode.window.activeTextEditor!.selection.active.line;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM