Home > OS >  Can concating two strings show resulting string
Can concating two strings show resulting string

Time:07-29

for the code:

const a = "url";
const b = "/route";
const c = a   b;

typescript knows the exact values of a and b, and since they're const, they're unchangeable. However, when concating both strings, c just shows a generic string type.

Is it possible for c to show url/route instead?

enter image description here enter image description here

CodePudding user response:

In order to infer literal type you need to use extra function for concatenation:

const a = "url";

const b = "/route";

const c = a   b;


const concat = <
    A extends string,
    B extends string
>(a: A, b: B): `${A}${B}` => `${a}${b}`

const result = concat(a, b) // "url/route"

Playground

In order to make type inference safe, in this case, you need to avoid using (plus) for string concatenation.

CodePudding user response:

The value of c is being updated on the runtime and if you print the log you will notice that the value of c is "url/route" its just that when you try to hover over c with the cursor since that code hasn't processed the result it doesn't display the updated value of c instead it shows the data type of variable value.

  • Related