这里我有一个名为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值丢失,我无法将这些值设置为可选项
发布于 2020-04-13 23:46:10
你的问题有两个方面。
首先,您不能为null或未定义的对象分配属性。换句话说,如果您的变量初始化为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方法。您是否事先知道哪些属性可以未定义,哪些属性不能?然后使用?运算符。
https://stackoverflow.com/questions/61190604
复制相似问题