There's a similar question but it's a different problem from mine found 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)
}
}
Will give an error inside when using the getRandomItem()
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)
What I'm trying to do (in case needed for a better understanding):
- create a variable containing an array with literal values
- create a type declaration (an union of literal) 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
As to why I need the first reason is because I need do a loop somewhere else.
Few "fixes" I found:
- removing
as const
from theapparelLocation
made it work but I can assign any value to location and not just those 4 - removing type annotation on the function and use a plain
array: any
also works but it's giving a warning
Apologies if it's an obvious mistake by me since I'm relatively new to typescript.