2 个回答
<script setup lang="ts">
import {  ElMessage } from 'element-plus'
import type {
MessageParams
} from 'element-plus'

let messagesObj = null

function message({ msg, showClose = true, type = "info" }) {
  if (messagesObj) return;

  if (typeof msg !== "object") {
    messagesObj = ElMessage({
      showClose,
      message: msg,
      type,
      onClose() {
        messagesObj = null;
      },
    } as MessageParams);
  }
}

</script>

<template>

</template>

因为 MessageOptions 中 type 字段的类型为

export const messageTypes = ['success', 'info', 'warning', 'error'] as const

而函数形参数上定义的类型是 string,string 的范围大于 "success" | "info" | "warning" | "error",因此 ts 会报类型错误。

这个时候需要缩小 type 的类型和 element-plus 定义的一致。

<script setup lang="ts">
import { ElButton, ElMessage, messageType } from 'element-plus'

let messagesObj = null

function message(msg, showClose: boolean = true, type: messageType = "info") {
  if (messagesObj) return;

  if (typeof msg !== "object") {
    messagesObj = ElMessage({
      showClose,
      message: msg,
      type,
      onClose: () => {
        messagesObj = null;
      }
    });
  }
}

</script>

<template>
  <ElButton @click="message('hello')">Show Message</ElButton>
</template>
推荐问题
logo
Microsoft
子站问答
访问
宣传栏