有点背景,我正在将我的源代码从Create React App迁移到Next.JS和TypeScript的编译方式有所不同。
看这个例子:
abstract class Parent {
constructor(val: any) {
this.init(val);
}
abstract init(val: any);
}
class Child extends Parent {
foo: string;
constructor(val: string) {
super(val);
}
init(val: any) {
this.foo = val;
}
}
const i = new Child('test');
console.log(i.foo);
我希望console.log
打印,test
但是可以打印undefined
(在TypeScript Playground中尝试过并可以正常工作)。
问题是我不确定哪个配置会导致这种奇怪的行为,我的第一个怀疑者tsconfig --> strictPropertyInitialization
试图将其设置为,false
但没有任何更改。
这是我的tsconfig.json
:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"jsx": "preserve",
"lib": [
"es5",
"es6",
"dom",
"es2015",
"es2017"
],
"moduleResolution": "node",
"allowJs": true,
"noEmit": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": false,
"preserveConstEnums": true,
"sourceMap": true,
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"experimentalDecorators": true,
"strictPropertyInitialization": false
}
}
任何帮助将不胜感激,
墨粉
因为您的目标是ESNext,所以JavaScript输出将类似于以下示例,该示例在现代浏览器中将输出“ test”。
class Parent {
constructor(val) {
this.init(val);
}
}
class Child extends Parent {
constructor(val) {
super(val);
}
init(val) {
this.foo = val;
}
}
const i = new Child('test');
console.log(i.foo);
如果您尝试在不支持ECMAScript类语法的较早版本的运行时中运行它,则将无法正常运行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句