Hot to fix "Type 'string' is not assignable to type 'T'"?
Use Overloading:
function createArray(length: number, value: string): string[];
function createArray<T>(length: number, value: T): T[];
function createArray<T>(length: number, value: T|string): (T|string)[] {
let result = [];
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;
}
console.log(createArray(3, 'x')); // ["x_0", "x_1", "x_2"]
console.log(createArray(3, 23)); // [23, 23, 23]
console.log(createArray(3, {hi: "hello"})); // [{
// "hi": "hello"
// }, {
// "hi": "hello"
// }, {
// "hi": "hello"
// }]
See demo.