typescript 打字稿类型错误:无法获取未定义或空引用的属性“拆分”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30353556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:00:48  来源:igfitidea点击:

Typescript TypeError: Unable to get property 'split' of undefined or null reference

typescript

提问by Blake Mumford

I'm trying to extract words from a string using the following:

我正在尝试使用以下方法从字符串中提取单词:

export class AddContactCtrl implements IAddContactCtrl {

    middleNamesString: string;

    saveContact() {
        var middleNames : string[] = this.middleNamesString.split(" ");
    }
}

However, I get the following error:

但是,我收到以下错误:

TypeError: Unable to get property 'split' of undefined or null reference

类型错误:无法获取未定义或空引用的属性“拆分”

Why is this the case? this.middleNamesStringis of type string, which should have the split()method, yet it returns null/undefined? I suspect it has something to do with the way I'm using this, but I'm not sure why.

为什么会这样?this.middleNamesString是 type string,应该有split()方法,但它返回空/未定义?我怀疑这与我使用的方式有关this,但我不确定为什么。

I've tried removing the middleNamesstring array type, to no effect. It does work if I change it to a local variable like so:

我试过删除middleNames字符串数组类型,但没有效果。如果我将其更改为局部变量,它确实有效,如下所示:

var randomString = "Random Name";
var middleNames : string[] = randomString.split(" ");

But why?

但为什么?

回答by NYCdotNet

Have you looked at the emitted JS? There's two possibilities.

你看过发出的JS吗?有两种可能。

The first is you're never assigning a value to middleNamesString. With the JS emitted from TypeScript classes, members don't exist until they get initialized with a value (or a placeholder like undefinedor null). If you haven't assigned a value to middleNamesString, then it is undefined, and you can't call .split()on undefined.

首先是你永远不会为 赋值middleNamesString。对于从 TypeScript 类发出的 JS,成员在使用值(或像undefined或 之类的占位符null)初始化之前不存在。如果你还没有分配一个值middleNamesString,那么undefined,你可以不叫.split()undefined

The other possibility is that with the way you're calling the method, thisis pointing to the global scope (such as the windowobject if your code is running in the browser.) In this case, you want to use an arrow function which will rewrite calls to thisto point to the current class instance in TypeScript (and ES6).

另一种可能性是,您调用该方法的this方式指向全局范围(例如,window如果您的代码在浏览器中运行,则为对象。)在这种情况下,您希望使用将重写的箭头函数调用以this指向 TypeScript(和 ES6)中的当前类实例。

saveContact = () => {
    var middleNames : string[] = this.middleNamesString.split(" ");
}

This still assumes that middleNamesStringhas been assigned a value before saveContact is called.

这仍然假设middleNamesString在调用 saveContact 之前已经分配了一个值。