[英]Set optional header into class in typescript
export default class ErrorResponseModel {
body: string
headers: object
statusCode: number
constructor(message: object, statusCode: number = 500, header?: {key: string, value: string}) {
this.headers = {
'Content-Type': 'application/json'
}
this.body = JSON.stringify(message)
this.statusCode = statusCode
if (header) {
this.headers[header.key] = header.value
}
}
}
我尝试将 header 设置为this.headers
,但出现错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.\n No index signature with a parameter of type 'string' was found on type '{}'.
我该如何处理这个错误? 我使用 TypeScript v4.7.4
您可以改为使用记录作为标题: headers: Record<string, string>
。 请参阅Typescript:类型“{}”没有索引签名
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.