【发布时间】:2023-01-28 08:44:00
【问题描述】:
TypeScript 转译器不会为以下代码发出错误:
function test1(test: any) {
test2(test);
}
function test2(test: string) {
}
我预计此代码会发出错误,因为如果类型为“any”的对象可以毫无错误地传递给类型为“string”的参数,那么代码可能会导致在运行时将非字符串传递给 test2 .编译器知道这里存在潜在的类型安全违规应该是微不足道的吧?
我以为 TypeScript 的重点是在编译时确保类型安全?我在这里错过了什么?我需要在 tsconfig.json 中启用一个选项吗?
编辑:
我不认为我在上面包含的通用示例能够说明我的观点。这是我实际应用程序中的 sn-p。该代码是 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违背了 TypeScript 的目的,因为它不是类型安全的,这就是为什么许多 linters 和一些配置设置警告反对它。简单的解决方案:永远不要使用any。 -
@CertainPerformance 哪些设置会导致 TypeScript 发出使用 any 的警告?这正是我想要的。促使我发帖的问题是,我正在使用的库从特定函数返回 any[][],并且我将“any”对象之一传递给类型函数,但没有意识到发生了类型安全违规。显然,这意味着我实际上在代码中写入了一个错误,但我希望 TypeScript 会警告我这个错误,因为这实际上是静态类型检查的全部要点。
-
@CertainPerformance
noImplicitAny不起作用(不产生错误或警告)。我还有strict。 -
是的,因为你正在使用明确的任何 - 但
noImplicitAny帮助其他any问题。结合 strict 和 linter,你会很高兴。
标签: typescript