Looking at the generic function provided:
type Identity = <T extends string | number>(arg: T) => T;
const identity: Identity = (x) => x;
When attempting to use this function, errors arise when trying to reassign values.
let a = identity('a');
a = 'b'; // Error: Type '"b"' is not assignable to type '"a"'
let b = identity(1);
b = 2; // Error: Type '2' is not assignable to type '1'
The expectation was to receive either a string
or a number
from identity
, but it seems that literal types like 'a'
and 1
are being returned. Why is this happening? Is there a way to adjust constraints to change this behavior?
Two workarounds were discovered. The first involves assigning the parameter to a variable before using it:
let a_param = 'a'
let a = identity(a_param);
a = 'b'; // Success
let b_param = 1;
let b = identity(b_param);
b = 2; // Success
The second workaround includes casting to a string
or number
:
let a = identity('a' as string);
a = 'b'; // Success
let b = identity(1 as number);
b = 2; // Success
Both of these solutions may seem unconventional. It's possible that something may have been overlooked since still in the learning process with TypeScript.