【问题标题】:Typescript is not allowing empty object initialization打字稿不允许空对象初始化
【发布时间】:2020-07-26 04:08:08
【问题描述】:

这里我有一个名为 body 的变量,它稍后会接收一些数据,现在它被分配为 null:

const body: {
    "name": string,
    "photo": {
        "fileName": string,
        "file": NodeJS.ReadableStream,
        "encoding": string,
        "mimetype": string,
        "sizeInBytes": number,
        "publicUrl": string
    },
    "token": string
} = null;

但后来当我收到数据并尝试像这样放置数据时:

body[someVariable] = someVariable;

它编译时没有错误,但是当我运行 js 文件时,它给了我这样的错误:

Uncaught TypeError: Cannot set property 'fieldName1' of undefined

我在互联网上搜索,发现一个对象必须像 {} 空对象一样初始化才能在其中进一步添加属性,但如果我做类似的事情,例如:body = {} typescript error ays values are missing,我是无法将这些值设为可选

【问题讨论】:

  • 解决方法(body as object) = {};
  • 你可以改用const body = {} as {"name": string, ...etc... }。请注意,如果您不能将属性设为可选,那么理想情况下,您应该使用已经设置好的属性来初始化对象。为什么不能将属性设为可选?
  • 因为值来自网络服务,如果不是来自服务,我会手动输入其中一些值
  • 那为什么不const body: {...} = Object.assign(objWithDefaultValues, valueFromService);
  • 因为数据来自不同的结构并且数据很大,我只需要其中的几个,所以我从 web 服务响应中提取我需要的数据并像这样放入我的对象中:body[serviceRes.fieldName] = serviceRes.value跨度>

标签: node.js typescript interface typescript-typings


【解决方案1】:

您的问题有两个方面。

首先,您不能分配空对象或未定义对象的属性。其他 换句话说,如果你的变量被初始化为null,你就不能访问它的一个属性并给它赋值。这是一个 JavaScript 错误。

然后是 TypeScript 错误。看起来您想在对象上声明可选属性。你可以使用? 操作符:

const body: {
  name?: string,
  photo?: {
    fileName?: string,
    file?: NodeJS.ReadableStream,
    encoding?: string,
    mimetype?: string,
    sizeInBytes?: number,
    publicUrl?: string
  },
  token?: string
} = null;

或使用Partial 泛型类型:

interface BodyType {
  name: string,
  photo: {
    fileName: string,
    file: NodeJS.ReadableStream,
    encoding: string,
    mimetype: string,
    sizeInBytes: number,
    publicUrl: string
  },
  token: string
}

const body: Partial<BodyType> = {};

有关Partial 泛型的更多信息,请查看here

这样,您将能够指定对象的类型,而无需在初始化时填写每个声明的属性。理想情况下,您不会使用Partial,除非在特定情况下,而是在接口上声明哪些属性是可选的,哪些是强制性的。

无论如何,这取决于您的类型的含义。拥有BodyType 接口以及所有必需的道具是否有意义?然后选择Partial 方法。您是否事先知道哪些属性可以未定义,哪些不能?然后使用? 运算符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多