如何使用开玩笑和打字稿在对象上测试可能是两种不同类型的属性?
我有一个函数getFruit()
返回两种可能的类型,banana |苹果
。
我有一个开玩笑的单元测试,其中包括一种在其中一种类型上但不是另一种类型的属性测试。在这种情况下,香蕉
具有属性peel
,但Apple
没有。
test(`gets a banana`, () => {
const fruit = getFruit(id)
expect(fruit?.peel).toBeDefined();
})
我满足于水果?.peel
首次引用时可能无法定义它,因为我正在测试fruit?.peel
在同一行中定义。
但是,ts标记fruit?.peel
行有错误:
Property 'peel' does not exist on type 'Banana | Apple'.
Property 'peel' does not exist on type 'Apple'
如何使用JEST和TYSPRICT使用JEST和TYSPRICK的对象上测试属性?
i知道我可以用TS-ignore禁用TS编译器,但我希望解决方案而不是解决方法。
I have a function getFruit()
that returns two possible types, Banana | Apple
.
I have a jest unit test that includes a test for a property that exists on one of the types, but not the other. In this case, Banana
has the property peel
but Apple
does not.
test(`gets a banana`, () => {
const fruit = getFruit(id)
expect(fruit?.peel).toBeDefined();
})
I am content that fruit?.peel
may not be defined when it is first referenced, as I am testing for fruit?.peel
being defined in the same line.
However TS marks the fruit?.peel
line as having an error:
Property 'peel' does not exist on type 'Banana | Apple'.
Property 'peel' does not exist on type 'Apple'
How can I test a property on an object that may be of two different types using Jest and TypeScript?
I know I can disable the TS compiler with a ts-ignore, but I am hoping for a fix rather than a workaround.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然Typescript不能让您访问尚不清楚的属性,但它可以让您使用 operator中的
检查其存在:
或者正如Jonrsharpe指出的那样,最好做到最好。此:
在失败情况下输出:
而不是:
While TypeScript won't let you access a property that isn't known to exist, it will let you check for its existence with the
in
operator:Or as jonrsharpe points out, it may be better to do this:
which in the failing case outputs:
rather than: