Typescript - 类型有2种情况怎么办?

1,问题描述

现在有个需求:

接口返回的数据如下,data类型会随着 code 的值变化,并只有这2种情况

  • code === null时,data是对象
  • code !== null 时,data是字符串
{
	code: null,
	data: {
		status: 'success',
		order_no: 'a-b-c'
	}
}
{
	code: '006',
	data: 'xxxxxx'
}

定义的返回参数的类型:

type ResponseOrder = {
	code: string | null
	data: string | {
		status: string
		order_no: string
	}
}

在使用时会报错,虽然此时确定 data 是一个对象。

function getResult(): Promise<ResponseOrder> {}

const payResult = await getResult()
if (payResult.code === null) {
  // 报错:类型“string | { order_no: string; status: string; }”上不存在属性“status”ts. (ts2339)
  const status = payResult.data.status
}

2,问题解决

2.1,typeof 类型保护

typeof 是 JavaScript 中的运算符,表示操作数的类型

在 Typescript 中使用方法类似。在一个条件块中使用时,会推导出操作数的类型,相当于类型断言。

举例:

function doSome(x: number | string) {
  // 在 if 条件块中,明确告诉 TypeScript,x 的类型是 string
  if (typeof x === 'string') {
    console.log(x.abc(1)); // 报错: 'abc' 方法并没有存在于 string 上
    console.log(x.substring(1)); // ok
  }

  x.substring(1); // 报错:Error: 无法保证 x 是 string 类型
}

所以,上面的问题可以这样写

const status = typeof payResult.data === 'object' && payResult.data.status

2.2,联合类型

2种情况分开写

type ResponseOrder = {
  code: null;
  data:{
    status: string;
    order_no: string;
  }
} | {
  code: string
  data: string
};

2.3,断言为 any

没有办法的办法

const status = (payResult.data as any).status

以上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

下雪天的夏风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值