Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

TypeScript Argument of type 'ArrayValues' is not assignable to parameter of type 'string'

Good day! Help solve the problem. I decided to rewrite my components in TypeScript, and at the same time learn the language. I am trying to return a list of values by indices. The function can include two arrays, one consists of String, the other of 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));

Displays two errors:

Error 1. Conversion of type 'ArrayValues' to type 'HTMLElement' may be a
mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

Error 2. Argument of type 'ArrayValues' is not assignable to parameter of type 'string'.

Tell me how to fix it?

question from:https://stackoverflow.com/questions/65602494/typescript-argument-of-type-arrayvalues-is-not-assignable-to-parameter-of-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...