I have a service that returns an object with dates:

@Injectable() export class DateService { constructor() { } getNowDate(): Object { let d = new Date(); d.setHours(d.getHours() + 3); let dateHuman = d.toISOString(); let unixTimeStamp = Math.floor(d.getTime() / 1000) - (60 * 60 * 3); return { dateHuman: dateHuman, unixTimeStamp: unixTimeStamp }; }; } 

I use it in a component like this:

 import { DateService } from '../services/date.service'; @Component({ selector: 'app-question', templateUrl: './question.component.html', styleUrls: ['./question.component.scss'] }) export class QuestionComponent implements OnInit { constructor(private dateService: DateService) { } ngOnInit() { console.log(this.dateService.getNowDate()['dateHuman']); } } 

Everything is OK - the date is displayed. But if I try to display the date like this:

  ngOnInit() { console.log(this.dateService.getNowDate().dateHuman); } 

Then I get the following error:

Property 'dateHuman' does not exist on type 'Object'.

Explain, please, what is the reason for this phenomenon, why in this case the access to the property through a point and through a bracket are not equivalent?

  • and what's in the text: Property 'dateHuman' doesn’t exist on type 'Object'. it is not clear? - Grundy
  • Here it is just not clear. I return this property explicitly: return {dateHuman: dateHuman, unixTimeStamp: unixTimeStamp}; - cyklop77
  • no matter what you return, it is important what type you specified. - Grundy

2 answers 2

Problem in compiler check:

when accessed through a dot, the compiler checks whether the specified property is in the type or not

when accessed through parentheses - does not check.


In the example in question: the getNowDate method returns an object of type Object , this type does not have the dateHuman property, so the compiler throws the specified error during the check.

  • Do I understand correctly that by specifying private dateService: DateService in the constructor, I declared the type to be a private DateService? But how does the compiler know what kind of type it is (what properties does it have)? And is it possible to change it? - cyklop77
  • one
    @ cyklop77m is not correct. In the constructor, you declare a class field of type DateService . The compiler knows about this type, since you yourself indicated everything about it by adding the line import { DateService } from '../services/date.service'; - Grundy

The problem is in this line:

 getNowDate(): Object 

Here you declare that the getNowDate method returns an Object - and the Object type does not have a dateHuman property.

Remove the explicit indication of the return type of the method to allow the compiler to infer it from the return .

Alternatively, declare an interface that will return your method:

 interface IDateInfo { dateHuman: string; unixTimeStamp: number; } getNowDate(): IDateInfo