簡體   English   中英

輸入'字符串| ArrayBuffer' 不可分配給類型 'string'

[英]Type 'string | ArrayBuffer' is not assignable to type 'string'

從 FileReader 讀取字符串的 TypeScript 錯誤

讀取文件內容的簡單代碼:

const reader: FileReader = new FileReader();
       reader.readAsText(file);
       reader.onload = (e) => {
          const csv: string = reader.result; -> getting TS error on this line
}

我得到的打字稿錯誤:

Type 'string | ArrayBuffer' is not assignable to type 'string'.
  Type 'ArrayBuffer' is not assignable to type 'string'.

錯誤消息說明了一切。

您聲明了一個string類型的csv變量。 然后分配string | ArrayBuffer string | ArrayBuffer類型( reader.result )到string類型,你剛剛分配。 你不能。 您只能將string分配給string

因此,如果您 100% 確定reader.result包含string ,則可以斷言:

const csv: string = reader.result as string;

但是,如果您不確定,請執行以下操作:

const csv: string | ArrayBuffer = reader.result;
// or simply:
const csv = reader.result; // `string | ArrayBuffer` type is inferred for you

那么您通常應該進行一些檢查,例如:

if (typeof csv === 'string') {/*use csv*/}
else {/* use csv.toString() */}

無論csvstring還是ArrayBuffer這將始終輸出字符串。

const csv: string = typeof csv === 'string' ? csv : Buffer.from(csv).toString()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM