对于接口,可以使用 Partial<X>
,Mapped Type来表示"Permit all properties of X, but expect none of them" .
因此以下导致编译器错误:
interface X { foo: boolean }
function doSomething(x: Partial<X>) {
let aBoolean: boolean = x.foo; // ERROR: possibly undefined
}
doSomething({ foo: true }); // OK
doSomething({}); // OK
doSomething(true); // ERROR: Type 'boolean' has no properties in common with 'Partial<X>'
我想用 any
做同样的事情来说"this function may accept anything as a parameter, but you can't count on anything being there"
function doSomething(x: Partial<any>) {
let aBoolean: boolean = x.foo; // OK, but I wish it wasn't
}
doSomething({ foo: true }); // OK
doSomething({}); // OK
doSomething(true); // OK
doSomething(/* etc. */); // OK
我希望我的函数接受任何东西和一切作为参数,但在函数内部我不能访问对象的任何属性而不先检查它们 . 如果函数 x
中的类型为 void
或 never
,则甚至可以 .
我并不感到惊讶 Partial<any>
不能像我希望的那样工作 - 我绝对不会问“为什么 Partial<any>
按照我希望的方式工作” . 我在问:
What type can I use for the parameter x such that:
-
它接受任何/每种类型的参数
-
函数内部
x
的类型是每个属性可能未定义的东西(或x
的类型为void
等)
1 回答
它是空对象类型
{}
,它几乎与任何类型兼容,并允许您将几乎任何内容传递给doSomething
:但是在实现中没有任何了解它,如果不先检查就不能使用它: