[FIXED] Using Antd's message with typescript


I am using

"antd": "^4.21.3", "typescript": "^4.7.4" with react 18, and I am facing the problem of error config type! The error message is below..

// current code
import { message } from 'antd'

function AlertModal({ type = 'success', duration = 3, ...props }) {
const config = {
    duration: duration,
return message[type as keyof typeof message](config)
export default AlertModal

enter image description here

Does anyone have any idea how can I solve this annoying problem??


I’ll just rewrite what’s in the comments with some extra details, so that this question can be treated as answered.

The message import references the default export of this file which is typed as MessageApi, and the expression message[type as keyof typeof message] is evaluated as follows:

(content: JointContent, duration?: ConfigDuration, onClose?: ConfigOnClose) => MessageType
| (args: ArgsProps) => MessageType
| (options: ConfigOptions) => void
| (messageKey?: React.Key) => void
| () => [MessageInstance, React.ReactElement]

TypeScript in this scenario regards all of these function typings as equally possible so it tries to cast the config object as the first argument as each of those function types.

The problem arises when trying to cast an object to React.Key which is defined as string | number. config (or any object type) is just not a valid argument for that case and TypeScript is doing its job in warning you about that case.

However, in the implementation we can probably assume that certain special message types will not be called, such as the message type destroy. MessageApi['destroy'] is the only MessageApi function property that uses the React.Key argument, so removing (i.e. omitting) that typing would solve the issue. This can be easily done just by changing the keyof message cast to:

return message[type as keyof Omit<typeof message, 'destroy'>](config)

Answered By – 5ar

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published