qq309187341

新人首次使用 typescript 开发项目

  •  
  •   qq309187341 · Jan 4, 2022 · 2918 views
    This topic created in 1611 days ago, the information mentioned may be changed or developed.
    (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 replies    2022-01-04 11:33:11 +08:00
    murmur
        1
    murmur  
       Jan 4, 2022
    这一看就是 vue ,别折腾了,vue 的 ts 支持不是很完美
    TomatoYuyuko
        2
    TomatoYuyuko  
       Jan 4, 2022
    documentTitle 这个字段的类型你给的有问题了吧,不要联合一堆花里胡哨的类型,后面处理起来会很烦
    huijiewei
        3
    huijiewei  
       Jan 4, 2022
    to.name && allowList.includes(to.name)
    chenluo0429
        4
    chenluo0429  
       Jan 4, 2022
    和 vue 的 ts 支持又有何干?如果是和模板联合还有些类型推导有问题,单纯的 ts 代码谈什么支持不完美?

    to.name && allowList.includes(to.name)通过判断把 name 的类型收窄一下。另外 allowList 的类型定义为 RouteRecordName[]
    anguiao
        5
    anguiao  
       Jan 4, 2022
    name 有可能为 undefined 和 null , 所以不能直接作为 includes 的参数(要求参数是 string 类型)。如楼上所说,先判空就可以。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5456 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 08:54 · PVG 16:54 · LAX 01:54 · JFK 04:54
    ♥ Do have faith in what you're doing.