Home > Net >  Eslint & Typescript: named functions as const or class constructor: how to transform?
Eslint & Typescript: named functions as const or class constructor: how to transform?

Time:07-30

I am using frequently the code of an answer I've asked for:

function sameValuesAsKeys<K extends string>(...values: K[]): {readonly [P in K]: P} {
  const ret = {} as {[P in K]: P}
  values.forEach(k => ret[k] = k);
  return ret;
}

Since time goes on the Eslint from Angular nowadays complains about that function.

Use const or class constructors instead of named functions

I tried

const sameValuesAsKeys:<K extends string>=(...values: Array<K>): {readonly [P in K]: P} => {
  const ret = {} as {[P in K]: P};
  values.forEach(k => ret[k] = k);
  return ret;
}

which fails since it cannot find K and the approach like

const TEST={
    sameValuesAsKeys(...values: Array<K>):<K extends string> => ({readonly [P in K]: P}) => {

fails as well. Any hint how to format it properly to avoid the error from ESlint?

CodePudding user response:

It's just a syntax error. This compiles:

const sameValuesAsKeys = <K extends string>(...values: Array<K>): {readonly [P in K]: P} => {
  const ret = {} as {[P in K]: P};
  values.forEach(k => ret[k] = k);
  return ret;
}
  • Related