There's a question that resembles mine but addresses a different issue, which can be seen here: Argument of type '...' is not assignable to parameter of type '...' TS 2345
utils.ts (https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-types)
export function getRandomItem<T>(array: T[]): T {
return array[Math.floor(Math.random() * array.length)]
}
apparel.ts
import { getRandomItem } from "@/assets/ts/utils"
export const apparelLocation = ["HEAD", "TORSO", "ARMS", "LEGS"] as const
export type TypeApparelLocation = typeof apparelLocation[number]
// ...
export class Apparel {
/ ...
location: TypeApparelLocation
constructor(rating: number) {
// ...
this.location = getRandomItem(apparelLocation)
}
}
An error occurs when using getRandomItem()
within the code.
Argument of type 'readonly ["HEAD", "TORSO", "ARMS", "LEGS"]' is not assignable to parameter of type '("HEAD" | "TORSO" | "ARMS" | "LEGS")[]'. The type 'readonly ["HEAD", "TORSO", "ARMS", "LEGS"]' is 'readonly' and cannot be assigned to the mutable type '("HEAD" | "TORSO" | "ARMS" | "LEGS")[]'.ts(2345)
My goal with the code (for better understanding):
- Create an array with specific literal values
- Define a type declaration (a union of literals) from that array (TypeScript: Define a union type from an array of strings)
- Use that type as an annotation on a class attribute
- Select a random element from the array to assign to the
location
attribute
I need the array to be immutable for a loop in another part of the code.
Some "solutions" I came across:
- Removing
as const
fromapparelLocation
solved the issue, but it allows assigning any value tolocation
, not just the specified ones - Removing type annotation from the function and using
array: any
also resolved the problem, but it gives a warning
I apologize if the mistake seems obvious, as I am relatively new to TypeScript.