0

这两者有什么区别?

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

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

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

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

1 回答 1

0

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

const key = 'hello';

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

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

于 2021-12-12T11:56:24.220 回答