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

独自空忆成欢 提交于 2021-02-19 03:01:09

问题


I am using typescript to write a vs code extension and for some reason I am unable to get the current line.

The function I am trying to make is:

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

Which fails with error: Object is possibly undefined The import statement is:

import {window, commands, Disposable, ExtensionContext, StatusBarAlignment, StatusBarItem, TextDocument} from 'vscode';

What am I doing wrong?

(I am both new to TypeScript and writing extensions for VS code)


回答1:


activeTextEditor may be undefined. This indicates that there is no active editor and will happen for example when you first open a new workspace or when you close all editors

To fix, just add a quick check:

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



回答2:


Object is possibly undefined

Because there may or may not be an activeEditor.

You can do an explicit check:

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

Or an assertion if you are sure:

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


来源:https://stackoverflow.com/questions/49888986/vscode-api-why-cant-i-get-the-current-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!