Here’s the code with error:
let createArray = function<T>(length: number, value: T): T[] {
let result: T[] = [];
for (let i = 0; i < length; i++) {
if (typeof value === 'string') {
result[i] = value + '_' + i; // Type 'string' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'string'.
} else {
result[i] = value;
}
}
return result;
}
createArray(3, 'x');
I have no idea why Typescript can not recognize the Generics T
as string
in this case.
How can I fix it?