TSConfig文件详解08

2024-06-18  本文已影响0人  从零开始学ArchLinux

编译器配置项-compilerOptions

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

禁止未经检查访问索引签名-noUncheckedIndexedAccess

TypeScript 有一种描述对象的方法,这种方法可以通过索引签名来描述具有未知键但已知值的对象:

interface EnvironmentVars {
  NAME: string;
  OS: string;
 
  // Unknown properties are covered by this index signature.
  [propName: string]: string;
}
 
declare const env: EnvironmentVars;
 
// Declared as existing
const sysName = env.NAME;
const os = env.OS;
      const os: string
 
// Not declared, but because of the index
// signature, then it is considered a string
const nodeEnv = env.NODE_ENV;
        const nodeEnv: string

启用noUncheckedIndexedAccess选项将向未检查的属性字段添加undefined

declare const env: EnvironmentVars;
 
// Declared as existing
const sysName = env.NAME;
const os = env.OS;
      const os: string
 
// Not declared, but because of the index
// signature, then it is considered a string
const nodeEnv = env.NODE_ENV;
        const nodeEnv: string | undefined

禁止未使用的局部变量-noUnusedLocals

当存在未使用的局部变量时报告错误。

const createKeyboard = (modelID: number) => {
  const defaultModelID = 23;
'defaultModelID' is declared but its value is never read.
  return { type: "keyboard", modelID };
};

禁止未使用的参数-noUnusedParameters

当存在未使用的参数时报告错误。

const createDefaultKeyboard = (modelID: number) => {
'modelID' is declared but its value is never read.
  const defaultModelID = 23;
  return { type: "keyboard", modelID: defaultModelID };
};

严格模式-strict

strict选项支持广泛的类型检查行为,从而可以更好地保证程序的正确性。开启这个选项,相当于开启了接下来所有的strict mode相关的选项,你也可以根据需要关闭部分strict mode相关的选项。

在TypeScript未来版本中strick mode将引入额外的更严格的检查,所以当升级TypeScript的版本时程序中可能会出现新的错误,当然也会尽可能的引入一个选项来关闭额外的检查。

严格的bind、call、apply调用-strictBindCallApply

当启用了strictBindCallApply选项后,TypeScript将检查function的内置方法callbindapply的调用参数是否正确,例如下边的函数:

// With strictBindCallApply on
function fn(x: string) {
  return parseInt(x);
}
 
const n1 = fn.call(undefined, "10");
 
const n2 = fn.call(undefined, false);
Argument of type 'boolean' is not assignable to parameter of type 'string'.

否则,那些内置函数可以接受任意类型的参数,并返回any类型的值:

// With strictBindCallApply off
function fn(x: string) {
  return parseInt(x);
}
 
// Note: No error; return type is 'any'
const n = fn.call(undefined, false);
上一篇 下一篇

猜你喜欢

热点阅读