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

为啥 typescript 这行会报错?

  •  
  •   love · 2020-07-13 15:23:52 +08:00 · 2017 次点击
    这是一个创建于 1354 天前的主题,其中的信息可能已经有所发展或是发生改变。

    https://www.typescriptlang.org/play/index.html#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgeTBgQiQGc4BvAKDjrjJigH4AuBp5Ac2oF9rq6AK5JsxUnHQAKCETLtC48gEoqtegnRwpAQlkwyAOkZRVMABZQIAdzhJgtgKJQrUKcvV1spRg3YnuOABeOH0jE084b3J4EGC4AG0AckwkgF1DAFtMMCkAE2CAPjgCgGpQuWMmD3oon3gAT3jk1Izs3IKg4rzjMAAbBBgZSpNlVQB6cbg0Vz5qIA

    export interface Options {
        str?: string
    }
    
    function f(opts: Options) {
        if (!opts.str) throw new Error()
        const s: string = opts.str
        const x = ['a'].map(d => d + opts.str)
        const y = ['a'].map(d => d.split(opts.str)) // error: opts.str: Type 'undefined' is not assignable to type 'string | RegExp'.
    }
    
    3 条回复    2020-10-14 20:18:27 +08:00
    RRRSSS
        1
    RRRSSS  
       2020-10-13 15:36:15 +08:00
    因为 ts 不知道 opts.str 是 string 还是 undefined
    love
        2
    love  
    OP
       2020-10-13 16:03:07 +08:00
    @RRRSSS
    function f(opts: Options) {
    if (!opts.str) throw new Error() # A
    const s = opts.str
    const x = ['a'].map(d => d + opts.str)
    const y = ['a'].map(d => d.split(opts.str)) // error
    }

    可是行 A 不是已经排除掉 undefined 的可能了吗?
    下面的变量 s 的类型被自动推断为 string 而不是 string|undefined,看来原因就是 ts 子函数里所有的上层的类型断言会失效。
    TanMusong
        3
    TanMusong  
       2020-10-14 20:18:27 +08:00
    =>
    专业名词忘了,反正已经算另一个域了,判断只在这个方法里起作用
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5682 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 01:46 · PVG 09:46 · LAX 18:46 · JFK 21:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.