好的,我刚开始打字,我对以下代码中的Object is possibly undefined错误感到困惑(这段代码已高度缩写):

interface IUrlData {
    wsPropertyNames: string[];
    routeValuesRegExp: RegExp;
}

export default class Builder implements IBuilder {
    private _urlData?: IUrlData;
    async build(): Promise<IConfig> {
        // VS Code Intellisense says that this._urlData is IUrlData | undefined in the next line.
        if (this._urlData) {
            // In this next line, VS Code Intellisense says this._urlData is IUrlData (no undefined, so narrowed by the if).
            this._urlData.wsPropertyNames.forEach((value) => {
                const obj = wjConfig[value];
                if (isConfig(obj)) {
                    // This is where the error happens.  All of the sudden, this._urlData is back to IUrlData | undefined.
                    makeWsUrlFunctions(obj, this._urlData.routeValuesRegExp);
                }
            });
        }
    }
}

那么,有没有人可以帮我指出我的错误,或者提供一个解决办法,如果这是由于错误或类似的错误而被打字搞砸的东西?

非常感谢.

推荐答案

this._urlData赋值给局部变量,它应该会起作用.这是必需的,因为TypeScrip不能保证this._urlData不会在异步函数之间改变.

它将如下所示:

interface IUrlData {
    wsPropertyNames: string[];
    routeValuesRegExp: RegExp;
}

export default class Builder implements IBuilder {
    private _urlData?: IUrlData;
    async build(): Promise<IConfig> {
        const urlData = this._urlData;
        if (urlData) {
            urlData.wsPropertyNames.forEach((value) => {
                const obj = wjConfig[value];
                if (isConfig(obj)) {
                    // This is where the error happens.  All of the sudden, this._urlData is back to IUrlData | undefined.
                    makeWsUrlFunctions(obj, urlData.routeValuesRegExp);
                }
            });
        }
    }
}

Typescript相关问答推荐

类型断言添加到类型而不是替换

typescript抱怨值可以是未定义的,尽管类型没有定义

键集分页顺序/时间戳上的筛选器,精度不相同

状态更新后未触发特定元素的Reaction CSS转换

无法正确推断嵌套泛型?

对扩展某种类型的属性子集进行操作的函数

TypeError:正文不可用-NextJS服务器操作POST

Vue3 Uncaught SyntaxError:每当我重新加载页面时,浏览器控制台中会出现无效或意外的令牌

Typescript 类型守卫一个类泛型?

如何在脚本中输入具有不同数量的泛型类型变量的函数?

有没有办法在Zod中使用跨字段验证来判断其他字段,然后呈现条件

如何在try 运行独立的文字脚本Angular 项目时修复Visual Studio中的MODULE_NOT_FOUND

打字脚本错误:`不扩展[Type]`,而不是直接使用`[Type]`

作为参数的KeyOf变量的类型

如何在TypeScript中描述和实现包含特定属性的函数?

为什么 typescript 在对象合并期间无法判断无效键?

typeof 运算符和泛型的奇怪行为

如何在故事书的Typescript 中编写decorator ?

TypeScript 中的通用函数包装和类型推断

如何推断深层嵌套属性的类型?