【问题标题】:Index signature where key is string vs [string] [duplicate]索引签名,其中键是字符串 vs [字符串] [重复]
【发布时间】:2022-01-16 06:04:35
【问题描述】:

这两者有什么区别?

let foo:{ [index:string] : string } = {
    ['hello']: 'world'
};

let bar:{ [index:string] : string } = {
    'hello': 'world'
};

对于这两个值,我得到相同的结果 (world)

console.log(foo['hello'])
console.log(bar['hello'])

【问题讨论】:

标签: typescript index-signature


【解决方案1】:

第一个允许在方括号之间传递变量:

const key = 'hello';

let foo:{ [index:string] : string } = {
    [key]: 'world'
};

但是在您当前的示例中,您传递的是纯字符串,因此您使用的是带有静态键的动态语法。 ['hello']: 'world' 完全等同于 'hello': 'world'

【讨论】:

    猜你喜欢
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2020-01-12
    相关资源
    最近更新 更多