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
I want to know if we can use other than string as value in typescript
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/en-US/docs/Web/API/URLSearchParams/append
I want to know if we can use other than string as value in typescript
Share edited Oct 21, 2020 at 7:37 Jibin Thomas asked Oct 21, 2020 at 7:16 Jibin ThomasJibin Thomas 8743 gold badges11 silver badges27 bronze badges 6- What's your question? – Yoshi Commented Oct 21, 2020 at 7:17
- 1 maybe he wants to know how to force ts to accept other values than string – Sandro Schaurer 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 – Greedo 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. – Yoshi 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. – Teemu Commented Oct 21, 2020 at 7:22
2 Answers
Reset to default 5Typescript 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.
It works in browser because your browser is interpreting javascript code, not typescript. Typescript gets piled 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)