[英]Object definition in TypeScript
I currently have the following, in a TypeScript app: 我目前在TypeScript应用程序中具有以下内容:
interface Data {
url: string,
// more stuff
}
(...)
export class something() {
public data: Data;
}
method(){
this.data.url = "things";
}
The issue is that every time i try to give data.url a value, I get an error saying I cannot set the property url of undefined. 问题是,每次我尝试给data.url赋值时,都会收到一条错误消息,提示我无法设置undefined的属性url。 What am I doing wrong?
我究竟做错了什么? And why?
又为什么呢?
Thanks in advance! 提前致谢!
1) The class declaration syntax is wrong, it should be 1)类声明语法错误,应该是
export class something {
}
and NOT 并不是
export class something() {
}
2) method
is defined outside of the class, it should be inside the class 2)
method
是在类外部定义的,它应该在类内部
3) this.data
is not instantiated, it's undefined
, and you're trying to access url
property of an undefined
variable, hence the error. 3)
this.data
没有被实例化,它是undefined
,并且您试图访问一个undefined
变量的url
属性,因此出错。
interface Data {
url: string,
// more stuff
}
(...)
export class something {
public data: Data;
method(){
this.data = {
url: "things",
// more stuff
}
}
}
If you want to access method
from outside of the class, then you need to instantiate the class something
. 如果要从类外部访问
method
,则需要实例化类something
。
method() {
let obj = new something();
obj.data = {
url: "things",
// more stuff
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.