美好的一天! 帮助解决问题。我决定用 TypeScript 重写我的组件,同时学习这门语言。 我正在尝试按索引返回值列表。该函数可以包含两个数组,一个由 String 组成,另一个由 HTMLElement 组成。
// List string
const values1: string[] = ['str1', 'str2', 'str3', 'str4']
// List HTMLElement
const values2: HTMLElement[] = [new HTMLElement(), new HTMLElement()];
/**
* Returns array indices
*/
function getIndexList(): number[] {
return [2, 1];
}
/**
* Returns array value
*/
function getValues<ArrayValues>(values: ArrayValues[]): string[] {
const indexList = getIndexList();
let result: string[] = [];
indexList.forEach((ind) => {
if (values.length > ind) {
if (values[ind] instanceof HTMLElement) {
// error 1 here
result.push((values[ind] as HTMLElement).innerText);
} else {
// error 2 here
result.push(values[ind]);
}
}
});
return result;
}
console.log(getValues<string>(values1));
console.log(getValues<Element>(values2));
显示两个错误:
错误 1. 类型 'ArrayValues' 到类型 'HTMLElement' 的转换可能是一个
错误,因为两种类型都与另一种类型没有充分重叠。
如果这是故意的,请将表达式转换为“未知”
首先。
错误 2。“ArrayValues”类型的参数不可分配给“string”类型的参数。
告诉我如何修复它?