Home > OS >  Set optional header into class in typescript
Set optional header into class in typescript

Time:07-25

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
        }

    }
}

I try to set header into this.headers, but get an error:

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 '{}'.

How can I deal with this error? I use TypeScript v4.7.4

CodePudding user response:

You could use a record for headers instead: headers: Record<string, string>. See Typescript: type '{}' has no index signature

  • Related