【发布时间】:2020-02-01 12:49:37
【问题描述】:
我可以创建一个类型保护器,它断言对象中存在(或具有特定类型)的特定属性吗?
即
我有一个接口Foo:
interface Foo {
bar: string;
baz: number;
buzz?: string;
}
现在Foo 类型的对象将有一个可选的属性buzz。我将如何编写一个断言存在 Buzz 的函数:
即
const item: Foo = getFooFromSomewhere();
if (!hasBuzz(item)) return;
const str: string = item.buzz;
我将如何实现hasBuzz()?。类似于打字机的东西:
function hasBuzz(item: Foo): item.buzz is string {
return typeof item.buzz === 'string'
}
这样的东西存在吗?
PS:我明白我能做到:
const item = getFooFromSomewhere();
if (typeof item.buzz === 'string') return;
const str: string = item.buzz;
但我的实际用例要求我有一个单独的函数来断言 buzz 的存在。
【问题讨论】:
-
使用
"buzz" in item?
标签: typescript typeguards