[英]An object is created without a method of a class. Typescript error: Cannot invoke an object which is possibly 'undefined'. ts(2722)
Good evening!晚上好! I am newbie in javascript and typescript.
我是 javascript 和打字稿的新手。
I can't understand something.我无法理解一些东西。 I carefully typed my code and the situation appeared.
我小心地输入我的代码,情况出现了。 I can't imagine, why, through it's something basic.
我无法想象,为什么,通过它是一些基本的东西。 Look:
看:
class A {
id: number;
constructor(id:number){
this.id=4;
}
isIdZero?():boolean{
if(this.id===0)
return true;
else
return false;
}
}
let a : A= new A(0);
let b : A={
id:9
}
alert(b.isIdZero());
This code makes an error "Cannot invoke an object which is possibly 'undefined'. ts(2722)"此代码产生错误“无法调用可能是'未定义'的对象。ts(2722)”
Why?为什么? Function equals to what typed in {}, isn't it?
函数等于 {} 中输入的内容,不是吗?
How can I correct it?我该如何纠正?
My question is probably so primitive that I didn't find anything.我的问题可能太原始了,我什么也没找到。
isIdZero?():boolean{
The question mark here means you're defining isIdZero
so it may be undefined
, instead of being a function.这里的问号意味着您正在定义
isIdZero
所以它可能是undefined
,而不是一个函数。 Since it might be undefined, typescript won't let you call it unless you check it first.因为它可能是未定义的,除非你先检查它,否则 typescript 不会让你调用它。 Eg:
例如:
if (b.isIdZero) {
alert(b.isIdZero());
}
If you want isIdZero
to be a mandatory property, then remove the question mark.如果您希望
isIdZero
成为必需属性,请删除问号。 However, this change will cause the following code to start showing a type error, since the object doesn't have all the properties it needs to be an A:但是,此更改将导致以下代码开始显示类型错误,因为该对象不具备成为 A 所需的所有属性:
let b: A = {
id:9
}
You can either add the function to the object you're creating您可以将函数添加到您正在创建的对象
let b: A = {
id: 9,
isIdZero: () => false,
}
Or you can stop trying to call this an A, and just let it be an object with an id that's a number:或者,您可以停止尝试将其称为 A,而将其设为 id 为数字的对象:
let b = {
id: 9,
}
the ?这 ? operator you are using after isIdZero?
您在 isIdZero 之后使用的运算符? tells typescript that you expect a possibility of this property being undefined.
告诉打字稿您预计此属性可能未定义。
It doesn't seem like that's necessary, so you can remove that.这似乎没有必要,因此您可以将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.