Home > Enterprise >  Getting undefined parameter when using imported const
Getting undefined parameter when using imported const

Time:01-14

I have this const that I export to file and then I'm passing one value from it to function

export const STANDARD_COLORS: { [key: string]: number} = {
  notifyBlue: 0x1a72b5,
  deleteRed: 0xde3f51,
  newGreen: 0x12a571,
  updateOrange:0xffa74e
}

like this

.setColor(STANDARD_COLORS.newGreen)

but I get

Argument of type 'number | undefined' is not assignable to parameter of type 'ColorResolvable | null'.

Type 'undefined' is not assignable to type 'ColorResolvable | null'

When I try to pass it with ! like this

STANDARD_COLORS.newGreen!

error is gone but I have a hunch that is a lazy workaround to the actual problem

CodePudding user response:

This error only occurs with noUncheckedIndexedAccess, which implicitly adds undefined to your index signatures. Disabling this makes the error go away, but you might not want to do that if you want this extra level of strictness.

If you specify a type annotation on a variable TypeScript does not try to look in the assignment for the type of the variable, so it has no way to know for sure that newGreen is not undefined

If STANDARD_COLORS is static (ie the keys are known) and you are just using the type annotation to make sure the values in the object are numbers, you could use the satisfies operator instead:

export const STANDARD_COLORS = {
  notifyBlue: 0x1a72b5,
  deleteRed: 0xde3f51,
  newGreen: 0x12a571,
  updateOrange:0xffa74e
  red :"red" // error
} satisfies  { [key: string]: number };

setColor(STANDARD_COLORS.newGreen)

Playground Link

If you are using a version that does not have satisfy you could also use a function to enforce the constraint:

function makeColorTable<T extends Record<keyof T,number>>(c: T) {
  return c;
}
export const STANDARD_COLORS = makeColorTable({
  notifyBlue: 0x1a72b5,
  deleteRed: 0xde3f51,
  newGreen: 0x12a571,
  updateOrange:0xffa74e
  red :"red" // error
})

setColor(STANDARD_COLORS.newGreen)

Playground Link

  • Related