题目描述
题目来源及自己的思路
刚开始写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”。
###你这个函数 couponProcessorWithGeneric
接受的不是泛型参数 T[]
么?T
为啥会有 totalAmout
、quote
?
还是说你的意思是 T
一定会是个 CouponType2
?
那你 T extends CouponType2
限定一下吧:
couponProcessorWithGeneric<T extends CouponType2>(coupons: T[])
###<T>
-> <T extends { totalAmount: number, quote: number }>