Kheyonnant
Kheyonnant

Reputation: 23

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

Hello I have recently made the decision to switch from JS to TS for better coding but I am getting these errors from TypeScript, Validate function works perfectly fine in JavaScript.

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'

These are the files

//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)
        ///
    }
}

I have searched on Google but no one seem to have the same problem ? Am I writing the code wrong and how can I fix this?

Thank you so much!

Upvotes: 0

Views: 1118

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187014

This error tells you what is wrong:

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

Note the last bit | undefined. That means the the type of your variable could be the value you expect, or it might be undefined. If the value actually is undefined, then your program would crash here.

The problem is your Validate() function. It has this line:

if (!arg) return

And this line:

if (!isValid) return

So if arg or isValid are falsy, the function returns undefined. It only return the full object if it makes past those early return statements.

All that means that the return type of your function is:

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

To fix this you must test the value for existence before you treat this value as if it exists.

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

Typescript will notice that you checked the variable for existence, and let you proceed from inside that if statement.

Upvotes: 1

Related Questions