【发布时间】:2021-04-24 13:51:24
【问题描述】:
我对 TypeScript 有点陌生,想知道如何访问扩展接口的类的原始字段?
例如
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 的类型是什么?
它是某种特殊的 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);
}
}
【问题讨论】:
-
I'm not sure what the type of [name: string]: string | undefined is?它是一个字符串索引对象,允许值为string或undefined类型。 -
好的,谢谢迈克!那么如何将其提取到它自己的变量中呢?
-
请编辑您的问题,因为不清楚您的代码的问题出在哪里或什么问题,或者您想用它做什么
-
"访问类的原始字段" - 它们就是类实例的原始属性。普通对象属性。没有“基础地图”之类的。
-
不明白,为什么这个问题被否决了? @user1974753 提供了一个例子
标签: javascript typescript interface typescript-typings