#Property does not exist error

15 messages · Page 1 of 1 (latest)

agile lynx
#

So I have a check like this

var invalid = check(username, address);
if (invalid) {
        errorText.innerHTML = invalid.message;
        errorText.style.display = "block";
        return;
    }

and my function

function check(username: string, address: string): Error | boolean{
if (!username || typeof username !== "string" || username === "") {
        const err = new Error("Please provide a username.");
        return err;
}
return false

as you can see my check function returns an error or false if no error is present, in the first code block I check if error is present and then show message, but ts gives me this error "Property 'message' does not exist on type 'true | Error'.
Property 'message' does not exist on type 'true'

severe mural
#

multiple things

#

typeof username !== "string" is kinda useless

#

you told TS your function only accepts strings, so username won't ever be anything other that a string

#

!username and username === "" are redundant

#

an empty string ("") is falsy

#

so you don't need to check both, one check is enough

#

also, don't return Error

#

if your function didn't get the right arguments, throw an error instead

#

that you will catch where you call that check function

#

your check function doesn't need to return anything, its return type can thus be void

#

this leaves us with something like this

half harborBOT
#
Ascor8522#7606

Preview:```ts
function check(
username: string,
address: string
): void {
if (!username) new Error("Username cannot be empty.")
}

declare const errorText: HTMLDivElement
declare const username: string
declare const address: string

function foo() {
try {
check(username, add
...```

severe mural
#

@agile lynx

agile lynx
#

Ok thank you so much for the detailed explanation and tips, will change my code accordingly.