【发布时间】:2016-07-14 13:46:25
【问题描述】:
我是 TypeScript 的新手,但仍在尝试掌握其中的窍门。
我有一系列形成时间线的事件。它们看起来像这样:
const timeline = [{
type: 'payment',
amount: '12.23 USD',
when: '<iso timestamp>'
},{
type: 'payment',
amount: '12.23 USD',
when: '<iso timestamp>'
},{
type: 'refunded',
amount: '2.00 USD',
when: '<iso timestamp>'
},{
type: 'payment',
amount: '12.23 USD',
when: '<iso timestamp>'
},{
type: 'delinquent',
when: '<iso timestamp>'
}]
所以我已经将IEvent 定义为联合类型:
interface IPaymentEvent {
amount: string,
when: string
}
interface IRefundedEvent {
amount: string,
when: string
}
interface IDelinquentEvent {
when: string
}
type IEvent = IPaymentEvent | IRefundedEvent | IDelinquentEvent
问题是我很困惑如何在我的代码中使用这种类型信息。如何将该时间线转换为我刚刚定义的实际类型?以及在遍历数组时如何解构联合类型?
我的尝试是这样的:
class PaymentEvent implements IPaymentEvent {}
class RefundedEvent implements IRefundedEvent {}
class DelinquentEvent implements IDelinquentEvent {}
const duckTypeMap = {
payment: PaymentEvent,
refunded: RefundedEvent,
delinquent: DelinquentEvent
}
const typedTimeline = timeline.map(x => {
return duckTypeMap[x.type](x)
})
console.log(typedTimeline)
我觉得这里必须有一个常见的做法。如果有两种方法可以做到这一点,我也很感兴趣,(1)使用 es6 类和(2)没有 es6 类。对于后者,如果我们告诉它如何对 JSON 进行鸭式输入,类型系统似乎应该能够提供帮助。
【问题讨论】:
-
考虑使用字符串作为类型,如
interface IRefundedEvent { type: "refunded"; }。
标签: typescript