美文网首页
TSConfig文件详解07

TSConfig文件详解07

作者: 从零开始学ArchLinux | 来源:发表于2024-06-17 23:50 被阅读0次

编译器配置项-compilerOptions

类型检查相关配置项(四)

禁止隐式的this-noImplicitThis

默认值:strict模式为true,否则为false

this为隐式的any类型时,使用this的表达式将引发错误。

例如,下边的class返回了一个方法,这个方法试图访问this.widththis.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]方式不一定存在)。

相关文章

网友评论

      本文标题:TSConfig文件详解07

      本文链接:https://www.haomeiwen.com/subject/tjxfcjtx.html