TypeScript报错解决--Property 'target' does not exist on type 'typeof Dep'.ts(2339)

问题描述

demo代码:

	let uid = 0;
	Class Dep{
		constructor(){
			this.id = uid++; // vscode编译器报错
		}
	}

使用vscode编写typeScript文件,使this.id赋值时会提示报错,报错信息如下:

报错
error : Property 'id' does not exist on type 'Dep'.ts(2339)

官网:
2339错误 Property '{0}' does not exist on type '{1}'. 类型“{1}”上不存在属性“{0}”。

通过官网解释可以知道:
TS是静态类型的语言,就像我们用java类的语言,一定要提前定义,未定义的属性直接调用会报错。

解决办法1

第一种解决办法:将this.id 改为(this as any):id = uid++;

	let uid = 0;
	Class Dep{
		constructor(){
			(this as any).id = uid++; 
		}
	}

解决办法2

第二种解决办法:将this.id 改为this["id"] = uid++;

	let uid = 0;
	Class Dep{
		constructor(){
			this["id"] = uid++; 
		}
	}

解决办法3

除了以上的解决办法外,还有个最优解,根据提示我们是知道TS没有定义的语言不能直接调用,那么我们就在类里,定义类内的属性再去调用就可以解决了。
第三种解决办法:

	let uid = 0;
	Class Dep{
		id: number;
		constructor(){
			this.id = uid++; 
		}
	}
发布了18 篇原创文章 · 获赞 11 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_37800886/article/details/102934319