我创建了一个词法分析器等。我创建了一个名为 Error 的自定义调用,以及一个来自 Error 类的 LexerErr 类。 Error 类在其构造函数中接受许多变量,其中一个是一种类型,在本例中我尝试将其设置为“LexerError”,但是当我创建一个新实例时,该类型变得未定义,我是打字稿的新手,并且自从我尝试了在互联网上找到的所有东西后真的很困惑。 在此输入图片描述 代码 尝试#1
class Error {
type?: string;
constructor(){
if (type == undefined) {
this.type = 'Uncaught';
};
console.log(this.type);
};
};
class LexerErr extends Error {
type = 'LexerError';
};
new LexerErr()`
尝试#2
class Error {
type?: string;
constructor(type?: string){
if (type == undefined) {
this.type = 'Uncaught';
};
console.log(this.type);
};
};
class LexerErr extends Error {
constructor() {
super('LexerError');
};
};
new LexerErr();
我尝试将值分配给尝试#1中的类,但失败了,然后我尝试使用 super 方法在构造函数中分配它,如第二次尝试中所示
尝试 #1 有一个语法错误,因为
type
未定义。所以我真的无法回答任何问题。
尝试 #2 编译并运行,所以我可以告诉你为什么它不起作用。
constructor(type?: string) {
if (type == undefined) {
this.type = "Uncaught";
}
console.log(this.type);
}
在这里,除非
this.type
是 type
,否则你永远不会分配 undefined
。因此,当您致电 super("LexerError")
时,会发生以下情况:
Error
构造函数,并将 type
参数设置为 "LexerError"
。 type
现在是该函数的局部变量,与 this.type
无关。if (type == undefined)
为 false,因此该分支不执行。console.log(this.type)
返回未定义,因为 this.type
从未设置为任何值。如果您将其更改为:
constructor(type?: string) {
this.type = type ?? 'Uncaught'
console.log(this.type);
}
然后你会得到预期的
"LexerError"
。这里 this.type
总是被写入,所以它总是有东西。
或者,您可以使用类字段初始值设定项简写来接受构造函数参数并将其分配给类字段。
class Error {
constructor(public type: string = 'Uncaught') {
console.log(this.type);
}
}
请注意
public
,它将其声明为实例上的字段,将为您填充该字段。
另请注意,
type
参数有一个默认值。如果省略则将使用它。