我有個問題。我正在嘗試對資料進行編碼并在下載時進一步使用。所有功能都可以正常作業并提供我所期望的。但是在回傳發生的地方(在背景關系中)宣告格式常量時出現打字稿錯誤
錯誤:TS7053:元素隱式具有“任何”型別,因為“任何”型別的運算式不能用于索引型別“{作業表:字串;表:字串;}'。
下面是代碼。表是我通過 id 找到的 dom 樹中的一個元素
const template =
'<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-mic'
'rosoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta cha'
'rset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:Exce'
"lWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/>"
"</x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></"
"xml><![endif]--></head><body>{table}</body></html>";
const context = {
worksheet: "tablexls",
table,
};
const format = template.replace(/{(\w )}/g, (m, p) => context[p]);
uj5u.com熱心網友回復:
問題是 TypeScript 不知道這p是context. 也許您也不知道,因為您不能確定字串中的所有占位符實際上都是 ; 的有效鍵context。這取決于該字串的來源。
如果您想假設它是,那么完全型別安全的方法是使用以下幾行的型別斷言函式:
function assertsIsKeyOf<ObjectType>(object: ObjectType, key: string): asserts key is keyof ObjectType & string {
if (!(key in object)) {
throw new Error(`Key ${JSON.stringify(key)} expected but not found in object.`);
}
}
那么您的replace電話將是:
const format = template.replace(/{(\w )}/g, (m, p: string) => {
assertsIsKeyOf(context, p);
return context[p];
});
但是您可能不想做出這樣的假設,在這種情況下,您可能需要一個型別謂詞:
function isKeyOf<ObjectType>(object: ObjectType, key: string): key is keyof ObjectType & string {
return key in object;
}
然后呼叫是:
const format = template.replace(/{(\w )}/g, (m, p: string) => {
if (!isKeyOf(context, p)) {
// Do something to handle the fact th ekey isn't valid, like throwing an error,
// or returning a static value
throw new Error(`Template has invalid key ${JSON.stringify(p)}`);
}
return context[p];
});
以上所有內容的游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517334.html
上一篇:IsNaN顯示其他結果
