一些背景知识,我正在将我的源代码从 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 类语法的旧运行时中运行它,这将不起作用。
关于javascript - 在函数中初始化的 typescript 继承属性被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53613924/