[SOLVED] Typescript type assertion for "dynamic" record

Issue

I seem to be missing something, but the | AlertDynamic seems to break my typing suggestion

type Alert = {
  type: string
  variant: 'danger' | 'warning' | 'success' | 'info'
  message: string
}

type AlertDynamic = (arg: string) => Alert

export const alertTypeAuthentication: Record<string, Alert | AlertDynamic> = {
  incorrectPassword: {
    type: 'Incorrect password',
    variant: 'danger',
    message: 'Adgangskode er forkert.',
  },
  passwordCreated: (email: string) => ({
    type: 'Password created',
    variant: 'success',
    message: `We sendt a message to ${email}`,
  }),
} as const

When just using Record<string, Alert > I don’t see a type error for alertTypeAuthentication.incorrectPassword.message

Solution

Typescript won’t know that incorrectPassword is of type Alert, it will know it’s either Alert or AlertDynamic. It doesn’t matter that you used as const since the Record type is on the variable alertTypeAuthentication.

You can solve this by letting typescript infer the type itself, like this:

export const alertTypeAuthentication = {
  incorrectPassword: {
    type: 'Incorrect password',
    variant: 'danger',
    message: 'Adgangskode er forkert.',
  },
  passwordCreated: (email: string) => ({
    type: 'Password created',
    variant: 'success',
    message: `We sendt a message to ${email}`,
  }),
}

Or create a wrapper type like this:

type Alert = {
  type: string
  variant: 'danger' | 'warning' | 'success' | 'info'
  message: string
}

type AlertDynamic = (arg: string) => Alert

type AlertTypes = {
  incorrectPassword: Alert
  passwordCreated: AlertDynamic
}

export const alertTypeAuthentication: AlertTypes = {
  incorrectPassword: {
    type: 'Incorrect password',
    variant: 'danger',
    message: 'Adgangskode er forkert.',
  },
  passwordCreated: (email: string) => ({
    type: 'Password created',
    variant: 'success',
    message: `We sendt a message to ${email}`,
  }),
}

Answered By – ShamPooSham

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *