【问题标题】:How to extract type of Array member inside of member of Interface?如何在接口成员中提取数组成员的类型?
【发布时间】:2020-03-10 09:43:55
【问题描述】:

我如何提取 MyInterface2 中 key3 的类型以用于类似于 key2Value 的 key3Value?

interface MyInterface {
    key1: {
        key2: string
    }
}

const key2Value: MyInterface['key1']['key2'] = 'Hi' //Works fine

interface MyInterface2 {
    key1: {
        key2: Array<{ key3: string }>
    }
}

const key3Value: MyInterface2['key1']['key2']['key3'] = 'Hi' //Property 'key3' does not exist on type '{ key3: string; }[]'.(2339)

链接到typescript playground

【问题讨论】:

  • MyInterface2['key1']['key2'] 是一个数组,因此您需要像 const key3Value: MyInterface2['key1']['key2'][0]['key3'] = 'Hi' 一样对其进行索引
  • 相关(虽然不是骗人的):stackoverflow.com/questions/46376468/…

标签: arrays typescript types


【解决方案1】:

你必须添加一个索引才能进入数组:

const key3Value: MyInterface2['key1']['key2'][0]['key3'] = 'Hi'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2015-10-14
    • 2022-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 2021-03-15
    相关资源
    最近更新 更多