React Native迁移TS后报Cannot read property 'startsWith'错误
问题原因
报错TypeError: Cannot read property 'startsWith' of undefined是因为传入FileViewer.open()的路径值为undefined,库内部会对传入的路径字符串调用startsWith()方法做路径格式校验,拿undefined调用方法就会触发这个报错。
触发问题的具体代码bug是属性名大小写拼写错误:
RNHTMLtoPDF.convert()执行成功后返回的对象中,生成文件的路径属性为驼峰格式filePath(P为大写)- 你在「打开文件」按钮的回调里,写的是
openFile(file.filepath),这里filepath的p是小写,读取到的属性值不存在,返回undefined - 你给
openFile的入参标注了any类型,直接绕过了TypeScript的类型检查,所以这个拼写错误没有在编译阶段被捕获,直到运行时才触发报错。
修复方案
把错误的小写属性名改成正确的驼峰写法即可,修正后的代码如下:
const createPDF = async() => { let Options = { html: '<h1>test</h1>', fileName: 'test', directory: 'Download', }; let file = await RNHTMLtoPDF.convert(Options) Alert.alert('Alert','Successfully exported file:' + file.filePath,[ {text:'Cancel',style:'cancel'}, // 修正属性名大小写 {text:'Open',onPress:()=>openFile(file.filePath)} ],{cancelable:true}); } // 移除any类型,明确入参为string,后续传错类型TS会提前拦截报错 const openFile = (filepath: string) => { FileViewer.open(filepath) .then(()=>{ console.log(`Successfully export PDF file`); }) .catch(error => { console.log(error); }); }
优化建议
- 不要随便给参数标
any类型,会丢失TS的类型校验能力,这类低级拼写错误本来可以在编译阶段直接被拦截 - 可以引入对应依赖库的官方类型定义,给
RNHTMLtoPDF.convert()的入参、返回值补全类型标注,进一步降低拼写错误概率
内容的提问来源于stack exchange,提问作者KieuNamm
相关产品推荐
相关产品推荐

