typescript - 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 的自动化测试(没有运行时检查)。现在我基本上是通过一个演示应用程序来做的。
解决方案
推荐阅读
- clang - 为什么 Clang 不生成 libstdc++ 中某些库函数的位码?
- huggingface-transformers - 如何使用带有未标记文本的 run_mlm
- javascript - 根据多个搜索词过滤一组对象
- r - 通过 binom.test 或 prop.test 获得相同答案的方法
- javascript - 如何在Javascript中使用RegEx替换破折号后定位一个字母?
- android - 单击edittext时,我的miui/mobile主题崩溃了
- sql-server - 查看具有多个键列的表,并将其对应的值列放入对应的键列中
- flutter - Flutter Bloc 如何从 Widget 本身更新 BlocBuilder 中的 Widget?
- python - Python中的格式问题
- reactjs - React:加载图像之前的图像大小问题