简体   繁体   中英

TS2339: Property 'props' does not exist on type '{}'

I'm trying access a property of an object which can be {} .

So I'm doing something like this:

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

Although, even if I'm ensuring that .children is there, typescript complains that it does not exist (also in the if condition).

This is quite weird IMO, because if we're asserting that a property exists (or not) why would it complain?


Example:

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

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

  return variable.name;
}

This will throw Property 'name' does not exist on type '{}'. as it can be seen in TypeScript Playground

The error makes sense — it's not safe to access a property that may not exist. Replace it with:

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

  return '';
}

As to the first part of your question, It's hard to answer without knowing what method does.

I came across this while coding with StencilJS. When you create a Web Component with StencilJS, you also define a "tag" attribute for it. Then you refer to it using that tag everywhere else in your project. For eg if your Web Component is CustomDropdown, you will have

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

If you need to use this component in another component, you simply use the "tag":

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

If you use

    <CustomDropdown> 

you will get the above error on the attributes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM