代码之家  ›  专栏  ›  技术社区  ›  TheUnreal

Typescript-联合类型

  •  2
  • TheUnreal  · 技术社区  · 7 年前

    我创建了以下界面:

    export interface Message{
      date: Timestamp | Date;
    }
    
    interface Timestamp {
      seconds: number;
      nanoseconds: number;
    }
    

    不知道为什么-我得到以下错误:

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

    为什么编译器会搜索 seconds 在里面 Date 而且不适用于 Timestamp 类型

    1 回复  |  直到 7 年前
        1
  •  2
  •   Shaun Luttin    7 年前

    简短回答

    为什么编译器在日期中搜索秒,而不使用时间戳类型?

    使用联合类型时,编译器只允许访问属性 存在于所有类型上 .你的错误是因为 seconds 只存在于 Timestamp 而且也不是在 Date .

    实例

    这里我们创建一个 Message 这有一个 时间戳 因为它 date .

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

    在下面的代码中,编译器不知道这一点 日期 是一个 时间戳 .就编译器而言, 日期 要么是 日期 或者 时间戳 .

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

    铅字护卫

    为了给编译器提供更多信息,我们可以添加一个类型保护。然后编译器就会知道,在 if 声明,它正在处理一个 时间戳 .

    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;
    }
    

    关于 type guards is here .

    推荐文章