V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
qq309187341
V2EX  ›  TypeScript

新人首次使用 typescript 开发项目

  •  
  •   qq309187341 · 2022-01-04 11:03:31 +08:00 · 2150 次点击
    这是一个创建于 815 天前的主题,其中的信息可能已经有所发展或是发生改变。
    (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))
    })


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

    to.name && allowList.includes(to.name)通过判断把 name 的类型收窄一下。另外 allowList 的类型定义为 RouteRecordName[]
    anguiao
        5
    anguiao  
       2022-01-04 11:33:11 +08:00
    name 有可能为 undefined 和 null , 所以不能直接作为 includes 的参数(要求参数是 string 类型)。如楼上所说,先判空就可以。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2923 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 11:10 · PVG 19:10 · LAX 04:10 · JFK 07:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.