编译器配置项-compilerOptions
类型检查相关配置项(四)
禁止隐式的this-noImplicitThis
默认值:strict
模式为true
,否则为false
在this
为隐式的any
类型时,使用this
的表达式将引发错误。
例如,下边的class返回了一个方法,这个方法试图访问this.width
和this.height
,但是在getAreaFunction
中返回的方法的上下文并不是Rectangle
的实例。
class Rectangle {
width: number;
height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
getAreaFunction() {
return function () {
return this.width * this.height;
'this' implicitly has type 'any' because it does not have a type annotation.
'this' implicitly has type 'any' because it does not have a type annotation.
};
}
}
禁止通过属性的方式访问索引签名-noPropertyAccessFromIndexSignature
这个配置项是为了确保访问属性的方法(obj.key
或者obj[key]
)和类型中属性定义的方式相一致。
在没有这个配置项时,TypeScript允许通过obj.key
的方式访问未定义的属性字段:
interface GameSettings {
// Known up-front properties
speed: "fast" | "medium" | "slow";
quality: "high" | "low";
// Assume anything unknown to the interface
// is a string.
[key: string]: string;
}
const settings = getSettings();
settings.speed;
(property) GameSettings.speed: "fast" | "medium" | "slow"
settings.quality;
(property) GameSettings.quality: "high" | "low"
// Unknown key accessors are allowed on
// this object, and are `string`
settings.username;
(index) GameSettings[string]: string
当开启该配置项后,上边的写法将引发错误,因为通过.
的方式访问了未知的属性而不是[]
的方式。
const settings = getSettings();
settings.speed;
settings.quality;
// This would need to be settings["username"];
settings.username;
Property 'username' comes from an index signature, so it must be accessed with ['username'].
(index) GameSettings[string]: string
这个配置项的目的是通过访问属性的方式让你明确该属性是否一定存(如果通过obj.key
方式一定存在,如果通过obj[key]
方式不一定存在)。
网友评论