Skip to content Skip to sidebar Skip to footer

Why Is This Code Saying Type 'number' Is Not Assignable To Type 'never'

I am trying to create a string build function called addToCache and the parameters of the function is defined by an interface called Payloads So based on the key code of the string

Solution 1:

Helping typescript a little by creating separate type alias for cache works just fine!

export enum MyStringsTest {
  DEPART_IN_X_MINUTE = 'DEPART_IN_X_MINUTE',
  A_DRIVER_IS_ASKING_FOR = 'A_DRIVER_IS_ASKING_FOR'
}
export interface Payloads {
  [MyStringsTest.DEPART_IN_X_MINUTE]: number
  [MyStringsTest.A_DRIVER_IS_ASKING_FOR]: string
}

type Catch = {
  [K in keyof Payloads]?: (payload: Payloads[K]) => string
}

constcache: Catch = {}
function addToCache<K extends keyof Catch>(code: K, cb: Catch[K]): void {
  cache[code] = cb
}
addToCache(MyStringsTest.DEPART_IN_X_MINUTE, (data) =>`Depart in ${data} minutes!`)
addToCache(MyStringsTest.A_DRIVER_IS_ASKING_FOR, (data) =>`a driver is asking for ${data}`)

Bdw do you really need enum, you could very well get rid of that completely as follows

export interface Payloads {
  DEPART_IN_X_MINUTE: number
  A_DRIVER_IS_ASKING_FOR: string
}

type Catch = {
  [K in keyof Payloads]?: (payload: Payloads[K]) => string
}

constcache: Catch = {}
function addToCache<K extends keyof Catch>(code: K, cb: Catch[K]): void {
  cache[code] = cb
}

addToCache('DEPART_IN_X_MINUTE', (data) =>`Depart in ${data} minutes!`)
addToCache('A_DRIVER_IS_ASKING_FOR', (data) =>`a driver is asking for ${data}`)

Post a Comment for "Why Is This Code Saying Type 'number' Is Not Assignable To Type 'never'"