刚接触 TS 不久想用 vue+ts 加深理解
请求接口:
function getGoods(index: number) {}
我想限制传入的 index
的类型。
在调用的时候
const route = useRoute()
const index = parseInt(route.query.index)
getGoods(index)
发现 parseInt()
是报错的, 类型不符合
我要怎么给 query
里面的 index
添加类型注解呢?
刚接触 TS 不久想用 vue+ts 加深理解
请求接口:
function getGoods(index: number) {}
我想限制传入的 index
的类型。
在调用的时候
const route = useRoute()
const index = parseInt(route.query.index)
getGoods(index)
发现 parseInt()
是报错的, 类型不符合
我要怎么给 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.
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
TS 的错误信息其实写的挺明白的,为啥不照着改呢……
VueRouter 的
query
声明是这样的:这是一个字典结构,每一项可能是
string
也可能是个string?
的数组。而
parseInt
的声明是这样的:要求必须传入一个
string
,可你上面取出来的值 TS 并不能保证是个string
,所以就报错了。如果你确定你传入的就是
string
,那你类型断言一下就好了: