Home > Back-end >  Typescript: Type 'unknown' is not assignable to type 'BlendMode'
Typescript: Type 'unknown' is not assignable to type 'BlendMode'

Time:03-09

TypeScript question. I need to pass a random parameter from this set:

letters.add("NORMAL");
letters.add("COLOR");
letters.add("LUMINOSITY");

 function getRandomItem(letters) {
    let items = Array.from(letters);
    return items[Math.floor(Math.random() * items.length)];
}

Letters definition:

const letters = new Set();

// Add Values to the Set
letters.add("NORMAL");
letters.add("DARKEN");
letters.add("MULTIPLY");

to a rect.blendMode = getRandomItem(letters);. So, it's expected to get something like rect.blendMode = "NORMAL";.

But I got an error: Type 'unknown' is not assignable to type 'BlendMode | "PASS_THROUGH"'. How can I pass a string with "" from my set to a rect.blendMode = ...?

CodePudding user response:

The issue is that your getRandomItem function is not properly typed and TypeScript cannot defer what type it should return, so as a result it defaults to unknown.

Update your code to correctly type function parameters and return types as shown below:

function getRandomItem(letters: Set<BlendMode>): BlendMode {
    let items = Array.from(letters);
    return items[Math.floor(Math.random() * items.length)];
}

CodePudding user response:

I would do it with a typed array, unless you have a reason to use Set:

const allLetters = [
  "NORMAL",
  "DARKEN",
  "MULTIPLY",
  "COLOR",
  "LUMINOSITY",
] as const;

function getRandomItem(letters: typeof allLetters) {
  return letters[Math.floor(Math.random() * letters.length)];
}

const randomItem = getRandomItem(allLetters)
type TypeOfRandomItem = typeof randomItem

TypeOfRandomItem becomes

type TypeOfRandomItem = "NORMAL" | "DARKEN" | "MULTIPLY" | "COLOR" | "LUMINOSITY"

  • Related