Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript error when passing const array to generic function

I’d like to be able to choose a random element from the SHAPES array, while also keeping it as const so that the Shape type can be used elsewhere in the code. Ideally, I want to be able to use the below randomChoice function for both const and non-const arrays.

const SHAPES = [
  'circle',
  'square',
  'triangle',
] as const;
type Shape = typeof SHAPES[number];

console.log('Available shapes are:');
for (let shape of SHAPES) {
  console.log(`    ${shape}`);
}

function randomChoice<T>(arr: T[]): T {
  let index = Math.floor(arr.length * Math.random());
  return arr[index];
}
console.log('A random shape is:');
console.log(randomChoice(SHAPES));

When I run the above, I get this error:

C:\ts>npx tsc test.ts
test.ts:18:26 - error TS2345: Argument of type 'readonly ["circle", "square", "triangle"]' is not assignable to parameter of type 'any[]'.
  The type 'readonly ["circle", "square", "triangle"]' is 'readonly' and cannot be assigned to the mutable type 'any[]'.

18 console.log(randomChoice(SHAPES));
                            ~~~~~~

And if I change the last line to this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let choice = randomChoice(SHAPES);
console.log(choice);

I get a slightly different error:

C:\ts>npx tsc test.ts
test.ts:18:27 - error TS2345: Argument of type 'readonly ["circle", "square", "triangle"]' is not assignable to parameter of type 'unknown[]'.
  The type 'readonly ["circle", "square", "triangle"]' is 'readonly' and cannot be assigned to the mutable type 'unknown[]'.

18 let choice = randomChoice(SHAPES);
                             ~~~~~~

>Solution :

Using as const on SHAPES declares it as a readonly array. Remove as const if you can, or change the function definition to accept Readonly<T[]> (sandbox):

function randomChoice<T>(arr: Readonly<T[]>): T {
  let index = Math.floor(arr.length * Math.random());
  return arr[index];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading