简体   繁体   中英

How to access underlying raw field of an Interface in TypeScript?

I'm a bit new to TypeScript and wondering how can I access the raw field of a Class that extends an Interface?

eg

export interface APIGatewayProxyEventHeaders {
    [name: string]: string | undefined;
}

getMap(headers: APIGatewayProxyEventHeaders): Map<string, string> {
    const map: Map<string, string> = headers.getUnderlyingMap();
    return map;
}

So I want some nice way to achieve what that imaginary headers.getUnderlyingMap() call aims to do?

I'm not sure what the type of [name: string]: string | undefined [name: string]: string | undefined is?

Is it some special TypeScript construct? All I seem to be able to do is headers["xxx"] .

Thanks!

UPDATE:

Thanks for the help, I was able to just do this to achieve what I wanted:

export interface APIGatewayProxyEventHeaders {
    [name: string]: string | undefined;
}

export class InternalEvent {

    constructor(
        public reqHeaders: {}) {
    }

    static fromInternalEvent(headers: APIGatewayProxyEventHeaders): InternalEvent {
        return new InternalEvent(headers);
    }

} 

You can treat this type [name: string]: string | undefined [name: string]: string | undefined as an object (dictionary), where all keys are strings and values are either string or undefined.

Here you have several examples to understand it better:

interface Dictionary {
  [name: string]: string | undefined
}

const x: Dictionary = {
  name: 'John',
  surname: 'Doe'
} // ok

const y: Dictionary = {
  name: 'John',
  1: 'hello'
} // ok, because JS make coersion under the hood, so you can acces x['1']

/**
 * Indexed types are more generic, because you can use any key you want
 */

y['any key I want'] // valid, returns undefined
y['()=>{}'] // like I said, any key)


const z: Dictionary = {
  name: 23
} // error, value can be either string or undefined, but not number

APIGatewayProxyEventHeaders is an object, like this:

{
  key1: "somevalue",
  key2: "someothervalue",
  key3: undefined
}

That interface definition for the object means that you will need to test both the existence of a key, and the presence of a value. If both are true, then you have a string.

Like this:

// const obj: APIGatewayProxyEventHeaders

if (!!obj[key]) {
  // obj[key] is a string
}

if (obj.hasOwnProperty(key)) {
  // obj[key] is string | undefined
}

You can convert this object into an Map like this:

const map = new Map(Object.entries(obj))

Now you have a Map with the values in it. But there is not much advantage to this, because you don't have any additional type information - just a different data structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM