在下面的代码中,我有一个名为isLegacyPayment
的类型.然而,尽管使用了它,并且在期望字符串const stripeId: string = payment.stripeId
的行之前返回或抛出,它仍然认为payment.stripeId
可能为空.我试图让这个类型的GUGID工作,因为这个GUGID的反义词(判断它的字符串是否有效)与其他DEVisNotLegacyPayment
相比有一个非常令人困惑的名字.任何与isNot
有关的数字都会引起重大混乱.有没有可能让isLegacyPayment
人在下面工作?
type Payment = {
stripeId: null | string;
}
function isLegacyPayment<T extends Pick<Payment, 'stripeId'>>(payment: T): payment is T & { stripeId: null } {
return payment.stripeId === null;
}
function test() {
const payment: Payment = { stripeId: '12321' };
if (isLegacyPayment(payment)) {
throw new Error('Is legacy payment');
}
const stripeId: string = payment.stripeId; // The error is here it says "Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.(2322)
}