So I'm trying to create a more general function which can help me transform data from an object instead something else.
However, with my current implementation, I'm getting the typescript error
Element implicitly has an 'any' type because expression of type '"channel" | "id" | "name"' can't be used to index type '{ id: string; name: string; source: string; }'.
Property 'channel' does not exist on type '{ id: string; name: string; source: string; }'.
Since the keys may not be matching up, but I am unsure on how to make it into a proper generic function.
Code:
type channelCreateChanges = {
change_from : {}
change_to : {
id : string,
name : string,
source : string,
},
datetime : string,
operation : "create",
entity : "channel",
}
type channelUpdateChanges = {
change_from : {
id : string,
name : string,
source : string,
}
change_to : {
id : string,
name : string,
source : string,
},
datetime : string,
operation : "update",
entity : "channel",
}
type programCreateChanges = {
change_from : {
}
change_to : {
channel : string,
id : string,
name : string,
origin : string,
},
datetime : string,
operation : "create",
entity : "program",
}
type programDeleteChanges = {
change_from : {
channel : string,
id : string,
name : string,
origin : string,
}
change_to : {
},
datetime : string,
operation : "delete",
entity : "program",
}
type dataChangeRow = {
from : string,
to : string,
datetime : string,
operation : string,
entity : string
}
const programKeys = [
"id",
"channel"
] as const;
const channelKeys = [
"id",
"name",
] as const;
type allChanges = channelCreateChanges | channelUpdateChanges | programCreateChanges | programDeleteChanges
type allKeys = typeof programKeys | typeof channelKeys
function ANY_CHANGE_LOG_TO_ROWS (data : allChanges, keys : allKeys) : dataChangeRow[] {
const rows = [] as dataChangeRow[];
for (const key of keys) {
const row = {
datetime : data.datetime,
entity : data.entity,
operation : data.operation
} as dataChangeRow;
if (data.operation === "create") {
row.from = `-`;
row.to = `${key}: ${data.change_to[key]}`;
}
else if (data.operation === "update") {
row.from = `${key}: ${data.change_from[key]}`;
row.to = `${key}: ${data.change_to[key]}`;
}
else if (data.operation === "delete") {
row.from = `${key}: ${data.change_from[key]}`;
row.to = `-`;
}
rows.push(row);
}
return rows;
}
keycould bechannel, butchannelCreateChanges.change_todoes not have achannelproperty.