typescript - 为什么可以将类型为 'any' 的值传递给类型参数而不会出错?

标签 typescript

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/

相关文章:

typescript - 如何将空检查拉入 typescript 中的功能

typescript - 有没有办法在 Typescript 中动态地将键映射到不同类型的 getter/setter?

TypeScript 在尝试导入时无法定位模块(vue 文件)

javascript - TypeScript - 如何定义具有任何类型参数的函数类型

类的 TypeScript 绑定(bind)不起作用?

typescript - 为什么我不能间接返回对象文字来满足 TypeScript 中的索引签名返回类型?

typescript - 错误 : Cannot find module 'graphql/polyfills/objectValues'

typescript - 有没有办法避免 typescript 中臭名昭著的 that = this

javascript - 可观察与回调

Angular2/Rxjs : 'catch' on observable giving ProgressEvent instead of json from response