首页 > 解决方案 > Typescript 库中的运行时类型检查 - 值得吗?

问题描述

对 Typescript(和类型检查)仍然有些陌生,并且想知道围绕参数和道具等运行时类型检查涉及哪些最佳实践。

我目前正在创建一个 React 组件库,并在测试它们时突然想到,因为我使用的是 Typescript,所以我跳过了通常在 vanilla JS 中执行的运行时检查。虽然 TS 为 TS 消费者处理它很棒,但如果普通 JS 消费者没有提供正确的类型,他们将不会收到任何警告。

我应该采取惰性路线并避开非 Typescript 用户,还是手动添加运行时支持并为该支持编写测试会更好?如果我这样做,这显然是一项实质性的工作,并且似乎会部分破坏使用 Typescript 的目的......

相关问题:有没有办法基于 TS 编译器编写测试?假设 Jest 的非工作示例:

formatTags(tags: string[]): string {
  return tags.join(', ');
}

it('formatTags() fails with the wrong args', () => {
  let tagList: string = formatTags(); // TS Error (missing param)
  expect(tagList).toThrowTypescriptError('Property `tags` is missing on type...') // pseudo code

  taglist = formatTags(['a', 'b', 'c'], 'something else'); // TS Error (extra param)
  expect(tagList).toThrowTypescriptError('Argument of type `something else` is not assignable...') // psuedo code
}

这个想法是有一个使用 API 的自动化测试(没有运行时检查)。现在我基本上是通过一个演示应用程序来做的。

标签: typescriptunit-testing

解决方案


推荐阅读