javascript - 如何在 typescript 中使用联合类型

标签 javascript node.js typescript

我在一个项目中使用 typescript ,在其中的某些部分我必须使用联合类型。但是我收到了一些奇怪的错误消息,我不知道如何处理。
考虑以下类型:

type body = {
  [_: string]:
    | 'boolean'
    | 'number'
    | 'string'
    | {
        type: 'boolean' | 'number' | 'string'
        optional?: boolean
      }
    | {
        type: 'array'
        items: 'boolean' | 'string' | 'number'
        optional?: boolean
        [_: string]: any
      }
}
我正在使用 [_: string]:因为我应该能够使用任意键。该值可以是指示类型的字符串,也可以是提供更多详细信息的对象。
现在考虑以下函数:
function show(data: body) {
  console.log(data)
}
当我使用以下对象调用上述函数时:
const data = {
  username: { type: 'string', optional: false },
  address: { type: 'string' },
  city: 'string'
}
typescript 给出以下错误:

Argument of type '{ username: { type: string; optional: boolean; }; address: { type: string; }; city: string; }' is not assignable to parameter of type 'body'.


Property 'username' is incompatible with index signature.


Type '{ type: string; optional: boolean; }' is not assignable to type '"string" | "number" | "boolean" | { type: "string" | "number" | "boolean"; optional?: boolean | undefined; } | { [_: string]: any; type: "array"; items: "string" | "number" | "boolean"; optional?: boolean | undefined; }'.


Property 'items' is missing in type '{ type: string; optional: boolean; }' but required in type '{ [_: string]: any; type: "array"; items: "string" | "number" | "boolean"; optional?: boolean | undefined; }'.


我该如何解决这个问题?
谢谢

最佳答案

您可以明确声明您的属性是什么类型 data

const data: body = {
  username: { type: 'string', optional: false },
  address: { type: 'string' },
  city: 'string'
}
或投它
const data = {
  username: { type: 'string', optional: false },
  address: { type: 'string' },
  city: 'string'
} as body;

关于javascript - 如何在 typescript 中使用联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67909614/

相关文章:

javascript - 如何在 TypeScript 中对不同的数组类型使用过滤器

javascript - 通过输入文件名获取目录路径

javascript 函数在页面加载时调用,而不是在动态生成的表中单击按钮时调用

node.js - 如何只显示最新的文档?

node.js - npm 链接导致 javascript 语法错误

node.js - 使用nodejs从异步函数返回列表

javascript - 使用特殊字符时随机字符串 HTML 转义问题

javascript - 如何处理空洞的 promise

javascript - Typescript React.Js 文件上传事件 Ts2322 错误

typescript - 为什么我会收到此消息(错误 : TS2376) while running oak.?正文中的错误详细信息