【问题标题】:Typing jest test.each tagged template literal with typescript用打字稿键入 jest test.each 标记的模板文字
【发布时间】:2020-08-21 05:45:20
【问题描述】:

我正在尝试输入一个使用标记模板文字的玩笑test.each

test.each`
  height | text
  ${10}  | ${undefined}
  ${20}  | ${undefined}
  ${10}  | ${'text'}
  ${20}  | ${'text'}
`('$height and $text work as expected', ({ height, text }) => {
  //...
});
  • height 是一个数字
  • text 是字符串或未定义

我当然可以将我的类型添加到测试的函数参数中:

({ height, text }: { height: number, text: string? }) => {
  //...
});

但这不是我想要的。 test.each 接受泛型类型

test.each<MyType>`
  height | text
  // ...
`('$height and $text work as expected', ({ height, text }) => {
  //...
});

我想知道如何使用该类型来推断函数参数中的类型。

【问题讨论】:

  • test.each&lt;{ height: number, text: string? }&gt;?
  • 已经试过了,还是不行
  • 你能扩展一下“不起作用”吗?给你尝试过的minimal reproducible example

标签: typescript jestjs


【解决方案1】:

我遇到这个问题是因为我正在寻找相同的解决方案,但我得出的结论是这是不可能的,因为 each 函数的类型仅在传递的参数不是模板时才使用泛型字面形式。只有传入table 时才能使用泛型类型。

所以你的例子应该是这样的:

test.each<{ height: number; text: string | undefined }>([
    { height: 10, text: undefined },
    { height: 20, text: undefined },
    { height: 10, text: 'text' },
    { height: 20, text: 'text' },
])('$height and $text work as expected', ({ height, text }) => {
    //...
});

这是类型文件的链接。 @types/jest Each interface

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 2021-05-31
    • 2019-04-12
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2023-01-28
    相关资源
    最近更新 更多