对于Typescript(和类型检查)还是有些陌生,并且想知道有关运行时类型检查(如参数和props)的最佳实践是什么。
我目前正在创建一个React组件库,并在测试它们时想到,因为我使用的是Typescript,所以我跳过了通常在普通JS中执行的运行时检查。 TS可以为TS使用者处理它很好,但是普通的JS使用者如果没有提供正确的类型,则不会收到任何警告。
我应该走懒路线,避开非Typescript用户,还是手动添加运行时支持,再为该支持编写测试会更好?如果我这样做,这显然是一项艰巨的工作,并且似乎在某种程度上会破坏使用Typescript的目的...
相关问题:有没有一种方法可以基于TS编译器编写测试?假设玩笑的非工作示例:
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的自动化测试(不进行运行时检查)。现在,我基本上是通过演示应用程序来完成的。