关注代码段:
interface PalPay {
email: string;
someCode: string;
}
interface CreditCard {
cardNumber: string;
securityCode: string;
}
const payment: PayPal | CreditCard = {email: 'd@d.d', cardNumber: '1234', securityCode: 'abc'};
我设法创建了一个具有email
字段的CreditCard对象。
我怎么想使用typescript创建一个CreditCard或PalPay的对象?
这种行为有什么意义呢?在什么情况下这有用呢?
答案 0 :(得分:1)
联合类型定义一个对象,该对象可以是联合的一个组成部分,因此在您的示例payment
中可以是PayPal
或CreditCard
。您可以在运行时使用这些,payment
可以是或者,也许用户可以选择付款方式。联盟类型通常与类型警卫或受歧视的联盟相关联。请参阅此处查看more
因此,在您的示例中,可能会有一个更现实的例子:
interface PayPal {
type: "paypal"
email: string;
someCode: string;
}
interface CreditCard {
type: "credit"
cardNumber: string;
securityCode: string;
}
declare var userOption: boolean;
let payment: PayPal | CreditCard;
if (userOption) {
payment = {
type: "credit",
cardNumber: '1234', securityCode: 'abc'
}
} else {
payment = {
type: 'paypal',
email: 'd@d.d', someCode: 'abc'
}
}
// Later, we can check the type field,
// and since this field is present on both interfaces
// and typed to a string literal type
// the compiler can determine the type of payment
// in the branches if statement
if (payment.type === 'credit') {
console.log(payment.cardNumber); // payment is of type CreditCard
} else {
console.log(payment.email);// payment is of type PayPal
}
答案 1 :(得分:1)
你在那里滥用联合类型。它并不意味着将两个不同的实体组合在一起并将它们合并在一起。它可以用作参数类型,可以在相应的函数中处理,例如
#include "lint.h"
lint::lint() {}
在这里,我将interface PayPal {
email: string;
someCode: string;
pay: () => void;
}
interface CreditCard {
cardNumber: string;
securityCode: string;
pay: () => void;
}
handlePayment = (payType: PayPal | CreditCard) => {
payType.pay();
}
函数添加到接口,您可以在pay
的联合类型上调用handlePayment
。