I was developing VS code extension and try to create and add files/folders into the workspace. But there was an error came up "Object is possibly 'undefined'.ts(2532)". I am using latest typescript version which is "typescript": "^4.5.4". here's the code.
Error line: const projectRoot = vscode.workspace.workspaceFolders[0].uri.fsPath;
createFileOrFolder(taskType: 'file' | 'folder', relativePath?: string) { relativePath = relativePath || '/';
const projectRoot = vscode.workspace.workspaceFolders[0].uri.fsPath; // here's the error "Object is possibly 'undefined'.ts(2532)"
if (path.resolve(relativePath) === relativePath)
relativePath = relativePath.substring(projectRoot.length).replace(/\\/g, "/");
if (!relativePath.endsWith("/")) relativePath += '/';
const basepath = projectRoot;
vscode.window.showInputBox({
value: relativePath || '/',
prompt: `Create New ${taskType} (/path/subpath/to/${taskType})`,
ignoreFocusOut: true,
valueSelection: [-1, -1]
}).then((fullpath) => {
if (!fullpath) return;
try {
let paths = fullpath.split('>').map(e => e.trim());
let targetpath = taskType === 'file' ? path.dirname(paths[0]) : paths[0];
paths[0] = taskType === 'file' ? path.basename(paths[0]) : '/';
targetpath = path.join(basepath, targetpath);
paths = paths.map(e => path.join(targetpath, e));
if (taskType === 'file')
this.makefiles(paths);
else
this.makefolders(paths);
setTimeout(() => { //tiny delay
if (taskType === 'file') {
let openPath = paths.find(path => fs.lstatSync(path).isFile())
if (!openPath) return;
vscode.workspace.openTextDocument(openPath)
.then((editor) => {
if (!editor) return;
vscode.window.showTextDocument(editor);
});
}
}, 50);
} catch (error) {
this.logError(error);
}
});
}
Can anyone help me out to fix this problem?
This happens because
workspaceFoldersis defined as:Which means it can be
undefined.The reason: if you don't have any workspace open in VS Code, like an empty window or just single/random files,
workspaceFoldersproperty won't be defined.Your code must handle that situation, probably quiting/displaying a message on these scenarios
Something like: