You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 10:46:01