【问题标题】:How to access underlying raw field of an Interface in TypeScript?如何在 TypeScript 中访问接口的底层原始字段?
【发布时间】: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? 它是一个字符串索引对象,允许值为stringundefined 类型。
  • 好的,谢谢迈克!那么如何将其提取到它自己的变量中呢?
  • 请编辑您的问题,因为不清楚您的代码的问题出在哪里或什么问题,或者您想用它做什么
  • "访问类的原始字段" - 它们就是类实例的原始属性。普通对象属性。没有“基础地图”之类的。
  • 不明白,为什么这个问题被否决了? @user1974753 提供了一个例子

标签: javascript typescript interface typescript-typings


【解决方案1】:

您可以将此类型[name: string]: string | undefined 视为对象(字典),其中所有键都是字符串,值是字符串或未定义。

这里有几个例子可以更好地理解它:

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

【讨论】:

  • 第二个在 TypeScript 中会失败,因为索引类型必须是字符串。
  • @JoshWulf 你的意思是 y['1'] 吗?不,TS 不会失败,因为 JS 强制。
  • 啊,我认为尝试显式构建它不会转换。但你是对的。我测试了它,它会强制执行。
  • 前段时间,这对我来说是一个惊喜。我也不相信)))
【解决方案2】:

APIGatewayProxyEventHeaders 是一个对象,像这样:

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

对象的接口定义意味着您需要测试键的存在和值的存在。如果两者都是真的,那么你有一个字符串。

像这样:

// const obj: APIGatewayProxyEventHeaders

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

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

您可以像这样将此对象转换为地图:

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

现在您有了一个包含值的地图。但这并没有太大的优势,因为您没有任何额外的类型信息 - 只是不同的数据结构。

【讨论】:

  • 更简单:new Map(Object.entries(obj))
  • 谢谢,我认为有一个方便的方法!
猜你喜欢
  • 1970-01-01
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
  • 2018-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-01
相关资源
最近更新 更多