TL;DR
Query: How do I create a type converter in TypeScript that extracts the defined keys from objects typed with index signatures?
I am looking to develop a type "converter" in TypeScript that takes a type A as input and outputs a new type B with keys representing all the defined keys in A, accepting only strings as values, as shown in the example below:
type AToB<
T,
K extends keyof T = keyof T
> = { [id in K]: string };
const a = {
x : {}
}
const b : AToB<typeof a> = {
x : "here it works"
}
https://i.sstatic.net/DKwu9.png b works
However, when I apply this to an object that already has a type with an index signature defined, the keyof operator does not recognize the defined keys, as shown in the following example:
type AWithSig = {
[id : string]: {};
}
const aSig : AWithSig = {
y: {},
z: {}
}
const bSig : AToB<typeof aSig> = {
y : "here the keys",
z : "are not shown :("
}
I tested this in the TSPlayground (link here) and it does not recognize the defined keys in aSig.
https://i.sstatic.net/kpc14.png bSig doesn't work
https://i.sstatic.net/UtDs8.png bSig works if I define the keys manually