[英]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() */}
無論csv
是string
還是ArrayBuffer
這將始終輸出字符串。
const csv: string = typeof csv === 'string' ? csv : Buffer.from(csv).toString()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.