TypeScript 转译器不会为以下代码发出错误:
function test1(test: any) {
test2(test);
}
function test2(test: string) {
}
我预计此代码会发出错误,因为如果类型为“any”的对象可以无任何错误地传递给类型为“string”的参数,则代码可能会导致非字符串可以传递给运行时的 test2。转译器知道这里存在潜在的类型安全违规应该是微不足道的吧?
我认为 TypeScript 的重点是在编译时确保类型安全?我在这里错过了什么?有没有我需要在 tsconfig.json 或其他东西中启用的选项?
编辑:
我认为我在上面包含的通用示例并没有表达我的观点。这是我实际应用程序的一个片段。该代码是 Google Apps 脚本应用程序的一部分,我使用的是 @google/clasp
类型。
// 'sheet' is of type GoogleAppsScript.Spreadsheet.Sheet
// The return value of this function is any[][]
// There is nothing I can do to change this, it is an import from a library
const cells = sheet.getSheetValues(2, 1, -1, -1);
for (const cell of cells) {
const registration = cell[0]; // any
const profileName = cell[1]; // any
const uuid = cell[2]; // any
//
// The signature of this constructor is as follows:
// constructor(aircraft: InputAircraft, profileName: string, uuid: string)
//
// Passing 'any' to the parameters of this constructor does not cause any
// warning or error, even with strict=true in my tsconfig.conf or even
// with eslint set up with the @typescript-eslint/no-explicit-any rule
// turned on.
//
yield new InputProfile(registration, profileName, uuid);
}
最佳答案
any
是有意保留的,作为一种绕过 类型检查器的方式,用于处理遗留的非类型化 Javascript 代码。它应该仅在您有未键入或不易键入的代码的情况下使用。
使用 --strict
(包括 noImplicitAny
等),如果变量意外,您将收到警告类型any
。如果您编写 any
,编译器会假定您是认真的并且知道您在做什么。如果你真的不想使用 any
,那么 no-explicit-any
是您可以打开的 ESLint 设置。
关于typescript - 为什么可以将类型为 'any' 的值传递给类型参数而不会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71976478/