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?
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"
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.