gpt4 book ai didi

typescript - 你能在 Typescript 中执行智能类型吗?

转载 作者:行者123 更新时间:2023-12-02 02:19:06 25 4
gpt4 key购买 nike

假设我有这样的界面:

export interface Promotion {
title: string;
image?: string;
description?: string;
startDate?: string;
endDate?: string;
type: 'discountWithImage' | 'discount' | 'countdown';
}

现在我的问题是,因为我现在确定如果键 type 等于 'countdown' 那么 endDate 和 startDate 将不会是未定义的。有没有办法在 typescript 中做到这一点?所以类似:

export interface Promotion {
title: string;
image?: string;
description?: string;
startDate?: string;
endDate: Promotion.type === 'countdown' ? string : undefined;
type: 'discountWithImage' | 'discount' | 'countdown';
}

在 Playground 上解释的例子Playground

最佳答案

您可以使用generic type parameter来做到这一点。把它想象成你传递给你的类型的参数。

type PromotionType = 'discountWithImage' | 'discount' | 'countdown';

export interface Promotion<T extends PromotionType> {
title: string;
image?: string;
description?: string;
startDate?: string;
endDate: T extends 'countdown' ? string : undefined;
type: T;
}

你会像这样使用它:

declare const testA: Promotion<'discount'>
const endDateA = testA.endDate // undefined

declare const testB: Promotion<'countdown'>
const endDateB = testB.endDate // string

您甚至可以使用泛型函数来为您传递该类型参数:

function getPromotion<T extends PromotionType>(type: T): Promotion<T> {
return {} as Promotion<T> // Not a real implementation
}

const resultA = getPromotion('discount').endDate // undefined
const resultB = getPromotion('countdown').endDate // string

Playground


或者您可以定义 discriminated union根据 type 的值,界面略有不同。

// One interface for common values that all promotions share
export interface PromotionCommon {
title: string;
image?: string;
description?: string;
startDate?: string;
}

// The discount promotion type has no end date and discount type.
export interface PromotionDiscount extends PromotionCommon {
endDate: undefined;
type: 'discountWithImage' | 'discount';
}

// The countdown promotion type has an end date and a countdown type.
export interface PromotionCountdown extends PromotionCommon {
endDate: string;
type: 'countdown';
}

// The final Promotion type can be either a discount or a countdown
type Promotion = PromotionDiscount | PromotionCountdown


declare const promotion: Promotion // pretend we have a promotion of unknown promotion type
if (promotion.type === 'countdown') {
const endDate = promotion.endDate // type: string
} else {
const endDate = promotion.endDate // type: undefined
}

Playground

关于typescript - 你能在 Typescript 中执行智能类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66698081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com