Typescript 你能用打字机打字吗?

Typescript 你能用打字机打字吗?,typescript,types,Typescript,Types,假设我有这样的界面: 导出接口升级{ 标题:字符串; 图像?:字符串; description?:字符串; 起始日期?:字符串; endDate?:字符串; 键入:“折扣带图像”|“折扣”|“倒计时”; } 现在我的问题是,因为我现在可以确定,如果键type等于“倒计时”,那么endDate和startDate将不会未定义。有没有办法用打字脚本来做?比如: 导出接口升级{ 标题:字符串; 图像?:字符串; description?:字符串; 起始日期?:字符串; endDate:Promoti

假设我有这样的界面:

导出接口升级{
标题:字符串;
图像?:字符串;
description?:字符串;
起始日期?:字符串;
endDate?:字符串;
键入:“折扣带图像”|“折扣”|“倒计时”;
}
现在我的问题是,因为我现在可以确定,如果键
type
等于
“倒计时”
,那么endDate和startDate将不会未定义。有没有办法用打字脚本来做?比如:

导出接口升级{
标题:字符串;
图像?:字符串;
description?:字符串;
起始日期?:字符串;
endDate:Promotion.type=='countdown'?字符串:未定义;
键入:“折扣带图像”|“折扣”|“倒计时”;
}
在操场上解释的示例

您可以使用。把它想象成你传递给你的类型的论点

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;
}

你可以通过-
促销来实现这一点
可以是带有
类型:“折扣WithImage”|“折扣”
且没有结束日期的促销,也可以是带有
类型:“倒计时”
和结束日期的促销。你能提供一个例子吗?这与我想要的很接近,但是,这样做的想法也是,不应该定义类型,而应该根据if语句推断出某种类型。就像这样,如果我检查
object.type==='discount'
,那么在if语句中,
endDate
不会被定义发布一个游乐场链接查看我的更新,它以不同的方式处理这个问题。我建议使用联合方法,因为只需查看
类型
,就可以更容易地细化/保护变量。
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
// 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
}