unknown
“吃掉”任何其他成员,所以
unknown | { createdDate: Date } == unknown
(描述了这种行为
in the PR
)
未知的
可以通过以下方式缩小范围:
function f20(x: unknown) {
if (typeof x === "string" || typeof x === "number") {
x; // string | number
}
if (x instanceof Error) {
x; // Error
}
if (isFunction(x)) {
x; // Function
}
}
看来实现您想要的结果的唯一方法是使用自定义类型的保护(因为
typeof x === "typename" is not applicable and
instanceof`不适用于接口)
function foo(bar: unknown) {
const hasCreatedDate = (u: any): u is { createdDate: Date } => "createdDate" in u;
if (hasCreatedDate(bar)) {
alert(bar.createdDate);
}
}
或者你可以使用
Object
这不会吃掉任何其他工会成员
function foo(bar: Object | { createdDate: Date }) {
if ("createdDate" in bar) {
alert(bar.createdDate);
}
}
foo({aa: ""})