【问题标题】:Return type based on input type基于输入类型的返回类型
【发布时间】:2019-10-29 15:04:04
【问题描述】:

我知道有类似的问题,但我不明白。

如何将类型配置为具有 inputType = outputType

public addReadableTime(message: PublicMsg | PrivateMsg): PublicMsg | PrivateMsg {
   message.displayTime = moment(message.lastModified).format('HH:mm');
   return message;
}

// ...

const publicMsg = this.addReadableTime(publicMsg);

TS2322:键入“PublicMsg | PrivateMsg' 不可分配给类型 'PublicMsg'。 “PrivateMsg”类型中缺少属性“publicChannelMessageId”,但在“PublicMsg”类型中是必需的。

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    似乎您需要的是具有类型约束的通用方法:

    public addReadableTime<T extends PublicMsg | PrivateMsg>(message: T): T {
       message.displayTime = moment(message.lastModified).format('HH:mm');
       return message;
    }
    
    // ...
    const publicMsg2 = this.addReadableTime(publicMsg);
    

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 2020-06-02
      • 2020-09-04
      • 2019-06-07
      相关资源
      最近更新 更多