Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 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 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...