打字稿中 obj.prop 和 obj['prop'] 之间的区别?

hap*_*ing 5 object typescript babeljs

使用 @babel/parser 解析一些字符串并获取 ast 后,我​​在通过 obj.prop 类型记录 ast 时遇到错误,但在使用 obj['prop'] 类型时它可以工作

import { parse } from "@babel/parser";
import traverse from "@babel/traverse";

const ast = parse('{key: "something"}', {
    sourceType: "module",
    plugins: ["typescript"],
});

// Property 'declaration' does not exist on type 'Statement'.  Property 'declaration' does not exist on type 'BlockStatement'.ts(2339)
console.log(ast.program.body[0].declaration.properties);
// it's good
console.log(ast.program.body[0]["declaration"].properties);
Run Code Online (Sandbox Code Playgroud)

我对两种写作方式的区别感到困惑?

谢谢你的回答

Anu*_*j.T 1

您可以在 JavaScript/typescript 中访问对象的属性:

  1. 点属性访问器:object.property
  2. 方括号属性访问:object['property']

何时使用:

当提前知道属性名称时,选择点属性访问器。

例如。

const hero = {
  name: 'XYZ'
};
Run Code Online (Sandbox Code Playgroud)

这里的属性已经提前知道,所以我们可以使用 Hero.name

当属性名称是动态的(即在运行时确定)时,选择方括号属性访问器。

例如:

const property = 'name';
const hero = {
  name: 'XYZ'
};

// Square brackets property accessor:
hero['name'];   //output => 'XYZ'
hero[property]; //output => 'XYZ'
Run Code Online (Sandbox Code Playgroud)

这里的属性是在运行时确定的,因此我们使用方括号。

因此,如果您在运行时确定的属性上使用属性点访问器,打字稿会给您错误

英雄类型上不存在属性“名称”。

访问属性的方式没有好坏之分。根据您的具体情况进行选择。

详细解释请参见Dmitri Pavlutin。