5

The type of append method of URLSearchParams is append(name: string, value: string): void; in typescript.

I tried appending array & number it worked for me in the browser but gives error in typescript code.

In MDN I found an example where number is being used as a value https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/append

I want to know if we can use other than string as value in typescript

6
  • What's your question? Commented Oct 21, 2020 at 7:17
  • 1
    maybe he wants to know how to force ts to accept other values than string Commented Oct 21, 2020 at 7:20
  • you can convert the values to a string, or create some method overrides to handle the different input Commented Oct 21, 2020 at 7:21
  • @SandroSchaurer Maybe/Probably, but it's still better for them to ask, than it is for us to guess. Commented Oct 21, 2020 at 7:22
  • 3
    That's what TypeScript is for, it prevents stupid type errors. Arrays and numbers are not a part of an any URL, make an explicit conversion to string before assigning to another string. Commented Oct 21, 2020 at 7:22

2 Answers 2

5

Typescript is there to prevent errors, that happen by mistakenly using the wrong type.

A URL is per default a single string, therefore the method only needs to accept a string.

Using typescript, you can just do the following to cast the number to a string:

const num = 1;
whatever.append('param', num + ''); // or call num.toString()

JavaScript (without the Typescript overhead), just converts the number to a string as soon as you append it to the whole URL. That is happening internally inside the .append() function (or maybe even later).

But in JavaScript you could also pass a variable of instance Date. It is possible, but the .append() function probably gets confused, throws an error, or calls the default .toString() of Date which you might not want.

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

1 Comment

The number example is trivial. The interesting example is something like {names: ['Alice', 'Bob']}, where the javascript version works as expected but typescript doesn't seem to have an elegant solution. This is a perfectly reasonable use-case that existing pages often use.
1

It works in browser because your browser is interpreting javascript code, not typescript. Typescript gets compiled into javascript code before being ran - you cannot run pure typescript. Try converting your array and number to strings before calling the append function, ie:

var name = [0,1,2]
var value = 3
name = name.toString()
value = value.toString()
x.append(name, value)

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.