0

I am getting a typescript error from the following code:

if (this.$route?.query?.domainName) {
  this.setDomain(this.$route.query.domainName);
}

The above code throws the following error:

Typescript - Argument of type 'string | (string | null)[]' is not assignable to parameter of type 'string'

 if (this.$route?.query?.domainName) {
   this.setDomain(this.$route.query.domainName);
                  ^
 }

My setDomain function just accepts a parameter of type string like so:

setDomain(domain: string) {
  this.domainName = domain;
}

I don't understand how the parameter could ever be null as I am checking the object property exists using the nested ? after the object properties in the if statement. Why would it be throwing this error?

1
  • Your argument is still a nullable string, but your method only accepts a non-nullable string as parameter. You would need to cast your argument to a non-nullable string before passing it. Commented Mar 29, 2021 at 10:16

1 Answer 1

2

In your code, domainName could still be something other than a string - an array ((string | null)[]). Your conditional guard is only verifying that it's not a falsey value, not that it's a string.

If you check that it's a string, it should work. Note that this example will allow an empty string, which your current code won't.

declare const $route: null | { query: null | { domainName: null | string | (string | null)[] } }
declare const setDomain: (domain: string) => void;

if ($route?.query?.domainName) {
    // reproduces your error
    setDomain($route.query.domainName);
}

if (typeof $route?.query?.domainName == "string") {
    // no error
    setDomain($route.query.domainName);
}

See in the typescript playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.