Here is the code snippet provided. You can find the full code here
interface DataInterface {
a: string[];
b: string[];
c: number[];
d: number[];
e: boolean[];
x: string
y: number
}
const dataObject: DataInterface = {
"a": [
"{$prefix} {$x}"
],
"b": [
"temp {$x}"
],
"c": [
3.8
],
"d": [
0,
50
],
"e": [
true,
false
],
"x": "world",
"y": 1,
}
const tableArrays: {[index: string]:any} = {
a: ["{$prefix} {$x}"],
b: ["world {$x}"],
c: [0, 50],
d: [3.8],
e: [true,false],
}
for (const tableArray in tableArrays) {
dataObject[tableArray] = Array.from({
...tableArrays[tableArray],
length: 5,
})
dataObject[tableArray].fill(
tableArrays[tableArray][tableArrays[tableArray].length - 1],
tableArrays[tableArray].length
)
for (let i = 0; i < dataObject[tableArray].length; i++) {
if (typeof dataObject[tableArray][i] === 'string') {
dataObject[tableArray][i] = dataObject[tableArray][i].replace('{$x}', i)
dataObject[tableArray][i] = dataObject[tableArray][i].replace('{$prefix}', "hello")
}
}
if (tableArray === 'b') {
dataObject[tableArray].pop()
}
}
console.log(dataObject)
The error encountered reads as follows:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DataInterface'. No index signature with a parameter of type 'string' was found on type 'DataInterface'.
An attempt has been made to assert that the tableArray
variable will only be a key in DataInterface
using:
type BuildingTableKeys = keyof BuildingTable;
// Iterate over the keys of tableArrays
for (const tableArray of Object.keys(tableArrays) as BuildingTableKeys[]) {...}
This resulted in the error message:
Conversion of type '{ [index: string]: any[]; }' to type '(keyof DataInterface)[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
The attempt to change to 'unknown' introduced further errors.
Efforts to assert that index
is part of DataInterface
have also been made using in
and keyof
, but were unsuccessful:
const tableArrays: {[index: keyof DataInterface]:any}
yielded the error:
An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.
const tableArrays: {[index in DataInterface]:any}
resulted in:
Type 'DataInterface' is not assignable to type 'string | number | symbol'.
Various solutions mentioned here and here were attempted without success.