繁体   English   中英

从 JS 切换到 TS 时类型错误上不存在属性

[英]Property does not exist on type error when switching from JS to TS

您好,我最近决定从 JS 切换到 TS 以获得更好的编码,但是我从 TypeScript 收到这些错误, Validate function 在 Z686155AF75A60A0F6E9D80C1F7D 中工作得非常好。

Property 'user' does not exist on type '{ isValid: boolean; user: string; userLowercase: string; } | undefined'
Property 'userLowercase' does not exist on type '{ isValid: boolean; user: string; userLowercase: string; } | undefined'

这些是文件

//functions.ts
function Validate(arg) {
    if (!arg) return
    let query :string = arg.toString().replace("@", "")
    let regex = /^[a-zA-Z0-9._-]+$/
    let isValid = regex.test(query)
    if (!isValid) return
    let userLowercase :string = query.toLowerCase()
    return { isValid: true, user : query, userLowercase }
}

//firstCommand.ts 
import { Validate } from './functions'

class firstCommand extends Commands {
    async command() {
        if (!Validate(this.arg)) return
        const { user, userLowercase } = Validate(this.arg)
        ///
    }
}

我在谷歌上搜索过,但似乎没有人有同样的问题? 我是不是写错了代码,我该如何解决这个问题?

太感谢了!

此错误告诉您出了什么问题:

Property 'user' does not exist on type
  '{ isValid: boolean; user: string; userLowercase: string; } | undefined'

注意最后一点| undefined | undefined 这意味着变量的类型可能是您期望的值,也可能是undefined 如果该值实际上是undefined ,那么您的程序将在此处崩溃。

问题是您的Validate() function。 它有这一行:

if (!arg) return

而这一行:

if (!isValid) return

因此,如果argisValid是虚假的,则 function 返回undefined 如果它通过了那些早期的返回语句,它只会返回完整的 object。

这意味着您的 function 的返回类型是:

{ isValid: boolean; user: string; userLowercase: string; } | undefined

要解决此问题,您必须先测试该值是否存在,然后再将该值视为存在。

const validationResult = Validate(this.arg)
if (validationResult) {
  const { user, userLowercase } = validationResult
  // proceed...
}

Typescript 会注意到您检查了变量是否存在,并让您从该if语句内部继续。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM