Typescript泛型使用map遍历的问题

题目描述

image.png

题目来源及自己的思路

刚开始写ts,没想到什么优雅的处理方案,有没有人提供下思路

相关代码

type CouponType2 = {
  totalAmount: number | string; // 优惠券面值
  quote: number | string; // 满xx元可用
  type: 2,
}

let coupons2:CouponType2[] = [{
  totalAmount: 10,
  quote: 50,
  type: 2
}, {
  totalAmount: 20,
  quote: 100,
  type: 2
}]

function couponProcessorWithGeneric<T>(coupons:T[]):T[] {
  return coupons.map(coupon => {
      const {totalAmount, quote} = coupon

      return {
          ...coupon,
          totalAmount: `${totalAmount}元`,
          quote:`满${quote}可用`
      }
  })
}

coupons2 = couponProcessorWithGeneric<CouponType2>(coupons2)

你期待的结果是什么?实际看到的错误信息又是什么?

期待如何能断言totalAmount和quote一定是T里的属性。现在报错类型“unknown”上不存在属性“quote”。

阅读 4.2k
2 个回答

你这个函数 couponProcessorWithGeneric 接受的不是泛型参数 T[] 么?T 为啥会有 totalAmoutquote

还是说你的意思是 T 一定会是个 CouponType2

那你 T extends CouponType2 限定一下吧:

couponProcessorWithGeneric<T extends CouponType2>(coupons: T[])

<T> -> <T extends { totalAmount: number, quote: number }>

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题