Typescript 属性“currentTime”没有初始值设定项,并且未在构造函数中明确指定
我是TypeScript新手。目前我正在尝试学习TypeScript中的界面。以下是我的代码:Typescript 属性“currentTime”没有初始值设定项,并且未在构造函数中明确指定,typescript,Typescript,我是TypeScript新手。目前我正在尝试学习TypeScript中的界面。以下是我的代码: interface ClockInterface{ currentTime:Date; setTime(d:Date):void; } class Clock implements ClockInterface{ currentTime:Date;[**[ts] Property 'currentTime' has no initializer and is not defin
interface ClockInterface{
currentTime:Date;
setTime(d:Date):void;
}
class Clock implements ClockInterface{
currentTime:Date;[**[ts] Property 'currentTime' has no initializer and is not definitely assigned in the constructor.]**
setTime(d:Date){
this.currentTime =d;
}
constructor(h: number, m: number) { }
}
您处于严格模式,具体来说,strictNullChecks选项为true 因此,日期类型的变量必须是日期类型。由于您没有在构造函数中初始化currentTime,因此在调用setTime方法之前,该变量是未定义的。所以你违反了你的类型定义
初始化构造函数中的变量,或将类型更改为Date | undefined,或更改编译器设置。要删除此错误,请进入tsconfig.json并删除strict=true。它对我有效,它检查错误。添加!在名字后面唱: 某地!:一串 或 打开类型脚本配置文件 tsconfig.json并将此代码添加到编译器选项
"angularCompilerOptions": {
// ...
"strictPropertyInitialization": false
// ...
}
注意:这将使静态分析变得更弱