[英]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.