簡體   English   中英

將可選的 header 設置為 typescript 中的 class

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM