2
function aaa(cell: unknown): void {
  if(cell && typeof cell == 'object' && cell.hasOwnProperty('display') && 'display' in cell) {

    console.log(cell.display)
  }
}

Getting error - Property 'display' does not exist on type 'object'.(2339)

Playground link

Does anyone knows why?

threenary
  • 5
  • 1
  • 4

3 Answers3

2

This is happening because you are defining the type of cell to be unknown. If you define it as any then it will work.

See this answer for more background on the difference between the two.

From the announcement about unknown:

There are often times where we want to describe the least-capable type in TypeScript. This is useful for APIs that want to signal “this can be any value, so you must perform some type of checking before you use it”. This forces users to safely introspect returned values.

If you want to use unknown, then you should move your type-checking into a different function as suggested in the announcement, like so:

function hasDisplay(obj: any): obj is { display: any } {
    return !!obj && typeof obj === "object" && "display" in obj;
}

function aaa(cell:unknown): void {
  if (hasDisplay(cell))
    console.log(cell.display)
  }
}

And then this should compile.

Simona
  • 279
  • 1
  • 8
0

Because actually cell is an unknown object, thus Typescript can't infer the property you are trying to reach.

As Simona says in her answer, if instead you use any it won't complaint, thus I recommend checking this Stack Overflow question about differences between any and unknown.

I would pursue nevertheless as much as possible, to type the parameter, or eventually once you are sure about the unknown is no longer an unknown, you could coerce it to the type you are expecting.

threenary
  • 5
  • 1
  • 4
0

You can use cast ( (<T>obj).x where T is the type, and obj is your object instance to access property/method x ).

In your case you defined file as JSX which try to pars all <x> to a tag, so you can use as operator (obj as T).x, that convert your object.

if your object inherit a specific type, or it compiles to JS and later the type doesn't matter, you can even cast to your desired type, but if you do not do that, you have no idea about the type, and your function is simple, won't trouble you later, you may use any instead of T.


function aaa(cell: unknown): void {
  if(cell && typeof cell == 'object' && cell.hasOwnProperty('display') && 'display' in cell) {

    console.log((cell as any).display)
  }
}

aaa({display: 'abc'})

As you can see the type are different but it is parsable

class MyType {
  public display:string|undefined;
}

function aaa(cell: unknown): void {
  if(cell && typeof cell == 'object' && cell.hasOwnProperty('display') && 'display' in cell) {

    console.log((cell as MyType).display)
  }
}

class XyzType {
  public constructor(display:string){
    this.display = display;
  }

  public display:string|undefined;
}
aaa(new XyzType('abc'))
Hassan Faghihi
  • 1,888
  • 1
  • 37
  • 55