gpt4 book ai didi

typescript - 检查属性是否存在的类型保护

转载 作者:搜寻专家 更新时间:2023-10-30 21:09:53 26 4
gpt4 key购买 nike

我知道type guards可用于区分联合类型。但是是否可以检测传入的未知类型的属性是否存在?

此代码无效。

function foo(bar: unknown | { createdDate: Date }) {
if (bar.createdDate)
alert(bar.createdDate); //Doesn't work
}

这也不是:

function foo(bar: unknown | { createdDate: Date }) {
if ('createdDate' in bar)
alert(bar.createdDate); //Doesn't work
}

注意:将 bar 的类型更改为 any 确实有效,但编译器不会缩小 if 语句中的类型。它正在输入 bar.createdDate 作为 any

我也尝试过使用此函数的通用版本。

function foo<T extends (unknown | { createdDate: Date })>(bar: T) {
if ('createdDate' in bar)
alert(bar.createdDate); //Doesn't work
}

有没有办法确认未知类型的属性是否存在,然后让编译器适本地缩小类型?

最佳答案

在联合unknown中“吃掉”任何其他成员,所以unknown | { createdDate: Date } == unknown (此行为描述为 in the PR )

同样来自 PR,unknown 可以通过以下方式缩小范围:

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"不适用并且 instanceof` 不适用于接口(interface))

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: ""})

关于typescript - 检查属性是否存在的类型保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54030040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com