typescript 有没有办法忽略打字稿中的类型不兼容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14737518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:47:50  来源:igfitidea点击:

Is there a way to ignore type incompatibility in typescript?

typescript

提问by Christian Nielsen

I have been looking at using typescript with mongoose for MongoDB. Mostly it has been working great, but with certain types of quesites I get warnings from the typescript compiler.

我一直在考虑在 MongoDB 中使用 typescript 和 mongoose。大多数情况下它运行良好,但是对于某些类型的问题,我从打字稿编译器收到警告。

If I do an or like so:

如果我这样做或喜欢这样:

{"$or": [{done: {"$exists": false}}, {done:false}]} 

I get the following warning:

我收到以下警告:

Incompatible types in array literal expression: Types of property 'done' of types '{ done: { $exists: bool; }; }' and '{ done: bool; }' are incompatible.

Incompatible types in array literal expression: Types of property 'done' of types '{ done: { $exists: bool; }; }' and '{ done: bool; }' are incompatible.

I understand why, but is there a way to express this so the compiler will accept it?

我明白为什么,但有没有办法表达这一点,以便编译器接受它?

回答by Ryan Cavanaugh

You can type-assert any of the elements to anyto "turn off" type checking:

您可以对任何元素进行类型断言any以“关闭”类型检查:

[<any>{done: {"$exists": false}}, {done:false}]

Or, if you're initializing a variable, you can do something like this:

或者,如果您正在初始化一个变量,您可以执行以下操作:

var n: any[] = [{done: {"$exists": false}}, {done:false}]