2

I have created the following interface:

export interface Message{
  date: Timestamp | Date;
}

interface Timestamp {
  seconds: number;
  nanoseconds: number;
}

No idea why - I get the following error:

Property 'seconds' does not exist on type 'Date | Timestamp'.
Property 'seconds' does not exist on type 'Date'.

Why does the compiler searches for seconds in Date and doesn't work with the Timestamp type?

2
  • 1
    See this answer. Commented Nov 30, 2018 at 19:54
  • 2
    What code actually produces that error? Commented Nov 30, 2018 at 20:14

1 Answer 1

2

Short Answer

Why does the compiler searches for seconds in Date and doesn't work with the Timestamp type?

When working with a union type, the compiler only allows access to properties that exist on all the types. Your error happens because seconds only exists on Timestamp and not also on Date.

Example

Here we create a Message that has a Timestamp for its date.

const message: Message = {
  date: {
    seconds: 10, 
    nanoseconds: 10
  }
}

In the following code, the compiler doesn't know that date is a Timestamp. As far as the compiler is concerned, date is either a Date or a Timestamp.

// Property 'seconds' does not exist on type 'Timestamp | Date'.
// Property 'seconds' does not exist on type 'Date'.
const seconds = message.date.seconds;

Type Guards

To give the compiler more information, we can add a type guard. Then the compiler will know that, inside the if statement, it is dealing with a Timestamp.

if (!(message.date instanceof Date)) { 
    // now we know we are dealing with a Timestamp
    // the compiler will not output an error
    const seconds = message.date.seconds;
}

Documentation on type guards is here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.