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
Typescript TypeError: Unable to get property 'split' of undefined or null reference
提问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.middleNamesString
is 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 middleNames
string 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 undefined
or 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, this
is pointing to the global scope (such as the window
object if your code is running in the browser.) In this case, you want to use an arrow function which will rewrite calls to this
to 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 middleNamesString
has been assigned a value before saveContact is called.
这仍然假设middleNamesString
在调用 saveContact 之前已经分配了一个值。