[英]How to access underlying raw field of an Interface in TypeScript?
我对 TypeScript 有点陌生,想知道如何访问扩展接口的 Class 的原始字段?
例如
export interface APIGatewayProxyEventHeaders {
[name: string]: string | undefined;
}
getMap(headers: APIGatewayProxyEventHeaders): Map<string, string> {
const map: Map<string, string> = headers.getUnderlyingMap();
return map;
}
所以我想要一些好方法来实现想象headers.getUnderlyingMap()
调用的目的是什么?
我不确定[name: string]: string | undefined
[name: string]: string | undefined
的是?
它是一些特殊的 TypeScript 构造吗? 我似乎能做的就是headers["xxx"]
。
谢谢!
更新:
感谢您的帮助,我能够做到这一点来实现我想要的:
export interface APIGatewayProxyEventHeaders {
[name: string]: string | undefined;
}
export class InternalEvent {
constructor(
public reqHeaders: {}) {
}
static fromInternalEvent(headers: APIGatewayProxyEventHeaders): InternalEvent {
return new InternalEvent(headers);
}
}
你可以把这个类型[name: string]: string | undefined
[name: string]: string | undefined
为 object(字典),其中所有键都是字符串,值是字符串或未定义。
这里有几个例子可以更好地理解它:
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
是一个 object,像这样:
{
key1: "somevalue",
key2: "someothervalue",
key3: undefined
}
object 的接口定义意味着您将需要测试键的存在和值的存在。 如果两者都是真的,那么你有一个字符串。
像这样:
// const obj: APIGatewayProxyEventHeaders
if (!!obj[key]) {
// obj[key] is a string
}
if (obj.hasOwnProperty(key)) {
// obj[key] is string | undefined
}
您可以将此 object 转换为 Map,如下所示:
const map = new Map(Object.entries(obj))
现在您有了一个 Map ,其中包含值。 但这并没有太大的优势,因为你没有任何额外的类型信息——只是不同的数据结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.