vue 使用 ts 给 $route.queryd 的属性添加类型

刚接触 TS 不久想用 vue+ts 加深理解

请求接口:

function getGoods(index: number) {}

我想限制传入的 index 的类型。

在调用的时候

const route = useRoute()
const index = parseInt(route.query.index)
getGoods(index)

发现 parseInt() 是报错的, 类型不符合

我要怎么给 query 里面的 index 添加类型注解呢?

阅读 6.2k
2 个回答

TS 的错误信息其实写的挺明白的,为啥不照着改呢……

VueRouter 的 query 声明是这样的:

query: { [key: string]: string | (string | null)[] }

这是一个字典结构,每一项可能是 string 也可能是个 string? 的数组。

parseInt 的声明是这样的:

function parseInt(s: string, radix?: number): number;

要求必须传入一个 string,可你上面取出来的值 TS 并不能保证是个 string,所以就报错了。

如果你确定你传入的就是 string,那你类型断言一下就好了:

const index = parseInt(route.query.index as string);
// 或者
const index = parseInt(<string>route.query.index);

function parseInt(s: string, radix?: number | undefined): number

Converts a string to an integer.

@param s — A string to convert into a number.

@param radix
A value between 2 and 36 that specifies the base of the number in numString. If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. All other strings are considered decimal.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题