TS2339:类型“ {}”上不存在属性“ props”

时间:2019-01-13 16:41:11

标签: javascript typescript

我正在尝试访问对象的属性,该对象可以是{}

所以我正在做这样的事情:

// component is the object which can be emtpy {}
if (component.children) return method(component.children)

尽管,即使我确保.children在那里,打字稿仍会抱怨它不存在(同样在if条件下)。

这是非常奇怪的IMO,因为如果我们断言某个属性存在(或不存在),为什么会抱怨呢?


示例:

type OtherType = { name: string };
type TestType = {} | OtherType;

function method(variable: TestType): string {
  if (!variable.name) return ''

  return variable.name;
}

这会抛出Property 'name' does not exist on type '{}'.,就像在TypeScript Playground中看到的那样

2 个答案:

答案 0 :(得分:1)

该错误是有道理的-访问可能不存在的属性并不安全。替换为:

function method(variable: TestType): string {
  if ('name' in variable) {
      return variable.name
  }

  return '';
}

对于问题的第一部分,如果不知道method的作用就很难回答。

答案 1 :(得分:0)

我在用StencilJS编码时遇到了这个问题。使用StencilJS创建Web组件时,还为其定义了一个“标签”属性。然后,您可以在项目的其他任何地方使用该标记来引用它。例如如果您的Web组件是CustomDropdown,您将拥有

match path=(:A)-[:K]->(:B) 
return path, 1 as path_type
union
match path=(:D)-[:H]->(:C) 
return path, 2 as path_type
union
match path=(:F)-[:L]->(:G}) 
return path, 3 as path_type 

如果需要在另一个组件中使用此组件,只需使用“标签”:

    @Component({
    tag: 'custom-dropdown',
    styleUrl: 'customdropdown.scss',
    shadow: false
})

如果您使用

    <custom-dropdown> etc... </custom-dropdown>

您将在属性上遇到上述错误。