[英]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.您好,我最近决定从 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'
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!太感谢了!
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
注意最后一点| undefined
| undefined
. | undefined
。 That means the the type of your variable could be the value you expect, or it might be undefined
.这意味着变量的类型可能是您期望的值,也可能是undefined
。 If the value actually is undefined
, then your program would crash here.如果该值实际上是undefined
,那么您的程序将在此处崩溃。
The problem is your Validate()
function.问题是您的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
.因此,如果arg
或isValid
是虚假的,则 function 返回undefined
。 It only return the full object if it makes past those early return statements.如果它通过了那些早期的返回语句,它只会返回完整的 object。
All that means that the return type of your function is:这意味着您的 function 的返回类型是:
{ 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. Typescript 会注意到您检查了变量是否存在,并让您从该if
语句内部继续。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.