簡體   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