Reputation: 1457
I'm a bit new to TypeScript and wondering how can I access the raw field of a Class that extends an Interface?
e.g.
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
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);
}
}
Upvotes: 1
Views: 990
Reputation: 4877
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.
Upvotes: 1
Reputation: 33061
You can treat this type [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
Upvotes: 1