如何防止在 Typescript 中的函数调用中从 'any' 进行隐式转换

How to prevent implicit conversion from 'any' on function call in Typescript

考虑以下打字稿代码:

function eatString(str: string){
    console.log(str);
}

const anyObject: any = {
    junk: 3425234,
};

eatString(anyObject); // Compiles ok - by why?
eatString({something: "abc"}); // Doesn't compile - as expected

有没有办法通过 tsconfig 或 tslint 选项或其他方式阻止函数 eatString(str: string) 使用 any 参数?

我最初认为 noImplicitAny 可能会有所帮助,但在尝试并查看文档后,情况并非我所想。 no-any 对我来说不是一个选择,因为在某些情况下我仍然希望能够使用 any

如果这不可能,是否有我遗漏的原因?我在 typescript/javascript 工作的时间不长,但我已经被一些本可以避免的问题所困扰。

any 根据定义可分配给任何其他类型,因此当您将 anyObject 传递给参数 str 时,它将根据此规则兼容。

除非绝对必要,否则应避免使用 any。如果你不知道你应该使用 unknown 的类型,它与没有保护或断言的其他类型不兼容(参见 any 的区别)

function eatString(str: string){
    console.log(str);
}

const anyObject: unknown = {
    junk: 3425234,
};

eatString(anyObject); // error now

在这种特殊情况下,您应该让编译器推断 anyObject

的类型
function eatString(str: string){
    console.log(str);
}

const anyObject = { // inferred as { junk : number }
    junk: 3425234,
};

eatString(anyObject); // error now

您可以使用 tslint 禁止使用 any 作为类型注释(使用 this rule),但 any 可能仍会从外部 API 泄​​漏。