TypeScript 开发中的关键要点解析
1. 类型声明测试的挑战与解决方案
在类型声明测试中,存在一个严重问题。例如,有如下完整的类型声明文件:
declare function map<U, V>(
array: U[],
fn: (this: U[], u: U, i: number, array: U[]) => V
): V[];
declare module 'overbar';
这样的声明会给整个模块赋予 any 类型,虽然测试能通过,但会丧失类型安全性,而且模块内函数调用都会产生 any 类型,破坏代码的类型安全。
由于在类型系统内很难检测 any 类型,推荐使用类型检查器之外的工具进行类型声明测试,如 dtslint 。以下是使用 dtslint 对 map 函数进行测试的示例:
const beatles = ['john', 'paul', 'george', 'ringo'];
map(beatles, function(
name, // $ExpectType string
i, // $ExpectType number
array // $ExpectType string[]
) {
this // $Expect
超级会员免费看
订阅专栏 解锁全文
15

被折叠的 条评论
为什么被折叠?



