TypeScript转发程序不会为以下代码发出错误:
function test1(test: any) {
test2(test);
}
function test2(test: string) {
}我预计这段代码会发出一个错误,因为如果一个类型为' any‘的对象可以传递给'string’类型的参数而没有任何错误,那么该代码可能导致在运行时将一个非字符串传递给test2。对于转发程序来说,知道这里存在潜在的类型安全违规应该是微不足道的吗?
我认为TypeScript的目的是确保编译时的类型安全?我在这里错过了什么?我是否需要在tsconfig.json中启用什么选项?
编辑:
我不认为我上面包含的通用示例能让我理解我的观点。下面是我实际应用程序的一个片段。代码是Google脚本应用程序的一部分,我使用的是@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);
}发布于 2022-04-23 03:07:24
为了处理遗留的非类型化Javascript代码,any被有意地留出来作为类型检查器的一种方式。它只应在代码未键入或不能轻松键入的情况下使用。
使用--strict (其中包括noImplicitAny,以及其他内容),如果变量的类型为any,则会收到警告。如果编写any,编译器会假设您是认真的,并且知道您在做什么。如果您真的不想使用any,那么no-explicit-any是您可以打开的ESLint设置。
https://stackoverflow.com/questions/71976478
复制相似问题