新人首次使用 typescript 开发项目

2022-01-04 11:03:31 +08:00
 qq309187341
(property) _RouteLocationBase.name: RouteRecordName | null | undefined
Name of the matched record

类型“RouteRecordName | null | undefined”的参数不能赋给类型“string”的参数。
不能将类型“undefined”分配给类型“string”。ts(2345)


代码是这样的:

const allowList = ['login', 'register', 'registerResult'] // no redirect allowList

router.beforeEach((to, from, next) => {
NProgress.start(); // NProgress 开始
setDocumentTitle('1111') // 动态设置页面的标题
console.log(allowList.includes(to.name))
})


请问这样写?
2180 次点击
所在节点    TypeScript
5 条回复
murmur
2022-01-04 11:06:22 +08:00
这一看就是 vue ,别折腾了,vue 的 ts 支持不是很完美
TomatoYuyuko
2022-01-04 11:11:50 +08:00
documentTitle 这个字段的类型你给的有问题了吧,不要联合一堆花里胡哨的类型,后面处理起来会很烦
huijiewei
2022-01-04 11:12:37 +08:00
to.name && allowList.includes(to.name)
chenluo0429
2022-01-04 11:28:21 +08:00
和 vue 的 ts 支持又有何干?如果是和模板联合还有些类型推导有问题,单纯的 ts 代码谈什么支持不完美?

to.name && allowList.includes(to.name)通过判断把 name 的类型收窄一下。另外 allowList 的类型定义为 RouteRecordName[]
anguiao
2022-01-04 11:33:11 +08:00
name 有可能为 undefined 和 null , 所以不能直接作为 includes 的参数(要求参数是 string 类型)。如楼上所说,先判空就可以。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/826035

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX