【问题标题】:How to declare a complex type and cast data into it?如何声明一个复杂类型并将数据转换为它?
【发布时间】:2021-09-30 18:15:25
【问题描述】:

注意:我从 TypeScript 开始,来自 Golang 背景(和 Python - 但这对这个问题没有帮助

我正在尝试通过尽可能使用类型声明来改进我的 TS 代码。然而,有一个地方我不知道如何接近。

我有以下数据(目前是硬编码的,但最终会通过 API 检索为 JSON 数据):

编辑:根据 Kelvin 的评论,我将更精确地使用实际代码,不幸的是,这意味着引入了 Vue3 人工制品

// this defines a reactive variable, initialized to an empty Array.
// when looking at the type in my IDE, I see that it is []never
let allEvents = ref([])

// and later on I add some data (please discard the `.value` part, it comes from Vue3, pretend it is not there)

let allEvents.value = [
    {
      start: '2021-07-20T12:55:04.225937+02:00',
      end: '2021-07-20T14:55:04.225937+02:00',
      name: "qqc aujourd'hui",
      id: 'aaa',
      important: false,
    },
    {
      start: '2021-07-21T12:55:04.225937+02:00',
      end: '2021-07-21T14:55:04.225937+02:00',
      name: 'qqc demain',
      id: 'bbb',
      important: false,
    },
  ]

这会在编译我的代码时产生错误:

ERROR in src/components/googleCalendar.vue:88:11
TS2322: Type 'string' is not assignable to type 'never'.
    86 |           end: '2021-07-21T14:55:04.225937+02:00',
    87 |           name: 'qqc demain',
  > 88 |           id: 'bbb',
       |           ^^
    89 |           important: false,
    90 |         },
    91 |       ]

Another question 解决了never 方面的问题,我的理解是我应该以某种方式将此结构声明为对象数组,然后声明这些对象的结构。

我该怎么做?

在 Go 中,我会声明一个类型(结构数组),然后将数据转换为该类型。 TS中是否有等价物?

【问题讨论】:

  • 这是您关于该变量(赋值)的完整代码吗?如果您不指定类型,TypeScript 不会抱怨分配错误的类型。您的代码缺少导致此错误的重要部分。
  • @KelvinSchoofs:您的假设是正确的。我想避免引入 Vue3 组件,但这误导了我的问题,抱歉。我编辑了它。
  • 一般情况下,当你初始化一个像let a = []这样的数组时,typescript不知道那个数组的类型,所以它推断never[]并认为你只能传递空数组。你必须做类似let a: MyInterface[] = []

标签: typescript typeerror


【解决方案1】:

当您创建一个新变量并将其初始化为一个空数组时,TypeScript 将其视为never[],因为它只是不知道如何处理它。你可以给 TypeScript 一个 hint 尽管它实际上是什么类型,例如:

interface MyDataObject {
    start: string;
    end: string;
    name: string;
    id: string;
    important: boolean;
}

let allEvents = ref<MyDataObject[]>([]);

// Now this will check whether the given object matches the MyDataObject type
allEvents.push({
    // would complain now because we're missing start/end/name/...
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2018-12-24
    相关资源
    最近更新 更多