首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么可以在没有错误的情况下将类型'any‘的值传递给类型化参数?

为什么可以在没有错误的情况下将类型'any‘的值传递给类型化参数?
EN

Stack Overflow用户
提问于 2022-04-23 02:57:27
回答 1查看 430关注 0票数 3

TypeScript转发程序不会为以下代码发出错误:

代码语言:javascript
复制
function test1(test: any) {
    test2(test);
}

function test2(test: string) {

}

我预计这段代码会发出一个错误,因为如果一个类型为' any‘的对象可以传递给'string’类型的参数而没有任何错误,那么该代码可能导致在运行时将一个非字符串传递给test2。对于转发程序来说,知道这里存在潜在的类型安全违规应该是微不足道的吗?

我认为TypeScript的目的是确保编译时的类型安全?我在这里错过了什么?我是否需要在tsconfig.json中启用什么选项?

编辑:

我不认为我上面包含的通用示例能让我理解我的观点。下面是我实际应用程序的一个片段。代码是Google脚本应用程序的一部分,我使用的是@google/clasp类型。

代码语言:javascript
复制
// '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);
}
EN

回答 1

Stack Overflow用户

发布于 2022-04-23 03:07:24

为了处理遗留的非类型化Javascript代码,any被有意地留出来作为类型检查器的一种方式。它只应在代码未键入或不能轻松键入的情况下使用。

使用--strict (其中包括noImplicitAny,以及其他内容),如果变量的类型为any,则会收到警告。如果编写any,编译器会假设您是认真的,并且知道您在做什么。如果您真的不想使用any,那么no-explicit-any是您可以打开的ESLint设置。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71976478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档